tags: ‘vue’, ‘路由’
categories: ‘vue’, ‘路由’
Vue Router获取当前页面由哪个路由跳转
问题:判断当前页面是由那个页面跳转过来的,如果上一个页面带有id则访问对应的步骤,否则为步骤一
可以使用beforeRouteEnter,具体代码如下:
beforeRouteEnter (to, from, next) {
next();
console.log('当前页面路由', to, '上一个页面路由', from);
},
例子:
此例子的操作是:
1、step页面点击 `查看详情按钮` 进入detail详情页
2、detail详情页点击 `回退或者继续操作按钮` 返回step页面
3、step页面请求详情回到对应的步骤
step.vue
<template>
<div>
<div v-if="code==1">步骤一</div>
<div v-if="code==2">步骤二</div>
<div v-if="code==3">步骤三</div>
<Button @click="goRoute">查看详情</Button>
</div>
</template>
<script>
var _this = "";
export default{
data (){
return {
code: 1, // 步骤
requestData: {
id: 2, // 假设id为2
}, // 数据
}
},
methods: {
// 获取详情
getDetail(id){
_this.code = id; // 假设传入的id就是当前步骤
},
// 跳转到详情页
goRoute(){
_this.$router.push({name:"detail", query: {id: _this.requestData.id}});
}
},
created(){
_this = this;
},
beforeRouteEnter (to, from, next) {
next();
// 如果不是从进行中的订单进来
if(from.name == 'detail'){
console.log('路由', to, from);
if(from.query.id){
from.query.id ? _this.getDetail(from.query.id) : '';
}
}
},
}
</script>
detail.vue
<template>
<div>
<Button @click="$router.push('step')">继续操作</Button>
</div>
</template>