2022-03-03
阅读:73
在使用vue开发项目过程中,使用vue-router实现路由跳转,如果从列表页跳转到详情页,再由详情页跳转到另外一个详情页时(比如:一个商品详情跳转另外一个商品详情,或者文章详情)页面不会触发create、mounted 等生命周期函数,导致页面无法更新
这时我们需要使用vue-router中的导航守卫beforeRouteUpdate这个组件内的导航守卫
例如:有一个列表页,详情页
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path:'/detail/:id',
name:'Detail',
component:()=/> import('@/views/detail')
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
页面展示如下
当我们点击详情页下链接跳转到其他商品详情页后,页面没有更新,这种类似的场景下,我们需要使用组件内的导航守卫
详情页面模板修改如下
<template>
<div>
<div class="title"/>这是详情页{{id}}</div>
<div class="list">
<p v-for="item in list" :key="item.id">
<router-link :to="'/detail/'+ item.id">{{item.title}}</router-link>
</p>
</div>
</div>
</template>
<script>
export default {
name:"Detail",
data(){
return {
id:"",//详情id
list:[
{id:1,title:'商品名称1'},
{id:2,title:'商品名称2'},
{id:3,title:'商品名称3'},
{id:4,title:'商品名称4'},
]
}
},
created(){
this.init();
},
methods:{
init(){//初始化
//获取路由上的详情id
const {id} = this.$route.params;
this.id = id;
}
},
beforeRouteUpdate(to,from,next){
//组件内导航守卫
// 在当前路由改变,但是该组件被复用时调用
console.log(to);
console.log(from);
next();
this.init();
}
}
</script>
<style lang="scss" scoped>
.list{
margin-top: 50px;
}
</style>
再次点击详情页下的其他商品详情链接
页面可以更新了