路由守卫(生命周期)
分3块:全局守卫、路由独立守卫、组件内守卫
1、全局守卫 main.js
router.beforeEach((to, from, next) => {
// 全局前置守卫
// if(to.fullPath === '/shoppingCart'){
// //如果没有登录?对不起先去登录一下
// next('/login')
// }
console.log('1 beforeEach', to, from) next()
})
// 时间触发比 全局前置守卫慢些
router.beforeResolve((to, from, next) => {
// 全局解析守卫
console.log('3 beforeResolve', to, from)
next()
})
router.afterEach((to, from) => {
// 全局后置守卫、钩子
console.log('4 afterEach', to, from)
})
2、路由独立守卫 router.js
{
path: '/a',
name: 'pageA',
components:{
default:pageA,
ppp:Test
},
beforeEnter:(to,from,next)=>{
console.log('2 beforeEnter',to,from)
next()
},
},
3、组件内守卫 xxx.vue
export default {
beforeRouteEnter(to,from,next){
//这里 拿不到this
// 路由跳转,使用此组件时触发
console.log('beforeRouteEnter',to,from)
next()
},
beforeRouteUpdate(to,from,next){
//可以获取 this
// /a/123 /a/456 当 组件被复用时,触发此方法
console.log('beforeRouteUpdate',to,from)
next()
},
beforeRouteLeave(to,from,next){
//可以获取this
//路由跳转,不适用此组件时触发
console.log('beforeRouteLeave',to,from)
next()
}
}
vue的keep-alive用法和生命周期
//只有路径匹配到的 name 为 a 组件会被缓存
<keep-alive include="a">
<router-view></router-view>
</keep-alive>
// routes 配置文件
export default [
{
path: '/',
name: 'home',
component: Home,
meta: {
keepAlive: true // 需要被缓存
}
}, {
path: '/user',
name: 'user',
component: User,
meta: {
keepAlive: false // 不需要被缓存
}
}
]
初次进入时:created > mounted > activated;退出后触发 deactivated
再次进入:会触发 activated;事件挂载的方法等,只执行一次的放在 mounted 中;组件每次进去执行的方法放在 activated 中
route和router的区别 1.区别:this.route是当前激活的路由对象,包含了当前的路由信息。
console.log(this.$route);
{
fullPath:'/home' //包含查询参数和 hash 的完整路径
path:'', //当前路由路径,绝对路径
name:'Home',
meta:{auth:true}, //是否需要登录
hash:'',
params:{},
query:{id:1} //表示 URL 查询参数,相当于/home?id=1
matched:??
}
2.路由跳转方式
声明式:<router-link :to="">
编程式:this.$router.push();
1.字符串 this.$router.push('/home')
2.对象 this.$router.push({path:'home'})
3.命名的路由 this.$router.push({name:'home',params:{id:1}})
4.带查询参数 this.$router.push({path:'home',query:{id:1}})