<router-link>
的replace属性
- 作用:控制路由跳转时操作浏览器历史记录的模式
- 浏览器的历史记录有两种写入方式:分别为
push
和replace
,push
是追加历史记录,replace
是替换当前记录。路由跳转时候默认为push
- 如何开启
replace
模式:<router-link replace .......>News</router-link>
编程式路由导航
具体编码
//$router的两个API
this.$router.push({
name:'xiangqing',
params:{
id:xxx,
title:xxx
}
})
this.$router.replace({
name:'xiangqing',
params:{
id:xxx,
title:xxx
}
})
//作用在总体网页的导航中
this.$router.forward() //前进
this.$router.back() //后退
this.$router.go() //可前进也可后退
示例代码
this.$router.forward() //前进
this.$router.back() //后退
this.$router.go() //可前进也可后退
缓存路由组件
作用:让不展示的路由组件保持挂载,不被销毁。
具体编码:
要注意的是 include=“News” 这个"News"必须得是组件的名称
<keep-alive include="News">
<router-view></router-view>
</keep-alive>
场景: 想切换的时候输入框的内容还在,未被销毁
示例代码
缓存多个路由的写法: 比如: 8个里面有2个是要保持缓存的
两个新的生命周期钩子
-
作用:路由组件所独有的两个钩子,用于捕获路由组件的激活状态。
-
具体名字:
activated
路由组件被激活时触发。deactivated
路由组件失活时触发。
示例代码
activated — deactivated 互为一对钩子
解决的场景:
News组件是已经被路由缓存了,如果你切换到别的组件的时候,News组件是不会销毁的。
如果用的是mounted、beforeDestroy这一对钩子的话,当进行切换的时候,News组件不销毁,他不销毁就没办法调用到beforeDestroy();
所以路由 – 》 引出 路由组件所独有的两个钩子,用于捕获路由组件的激活状态,即使他被缓存在路由里,使用了这两个钩子,当切换出去时,News组件是会被销毁的(失活)
路由守卫
一、全局守卫
理解:
只要形成路由的跳转,黄色框内函数一定会被调用
//全局前置守卫:初始化时执行、每次路由切换前执行
router.beforeEach((to,from,next)=>{
console.log('beforeEach',to,from)
if(to.meta.isAuth){ //判断当前路由是否需要进行权限控制
if(localStorage.getItem('school') === 'atguigu'){ //权限控制的具体规则
next() //放行
}else{
alert('暂无权限查看')
// next({name:'guanyu'})
}
}else{
next() //放行
}
})
//全局后置守卫:初始化时执行、每次路由切换后执行
router.afterEach((to,from)=>{
console.log('afterEach',to,from)
if(to.meta.title){
document.title = to.meta.title //修改网页的title
}else{
document.title = 'vue_test'
}
})
例子:
运行结果
二、独享守卫
beforeEnter(to,from,next){
console.log('beforeEnter',to,from)
if(to.meta.isAuth){ //判断当前路由是否需要进行权限控制
if(localStorage.getItem('school') === 'atguigu'){
next()
}else{
alert('暂无权限查看')
// next({name:'guanyu'})
}
}else{
next()
}
}
写在配置项中
三、组件内守卫
区别: 前置和后置是当路由进行切换时,都会被调用
而组件内的守卫,切进去之后,如果不切出去,beforeRouteLeave是不执行的
//进入守卫:通过路由规则,进入该组件时被调用
beforeRouteEnter (to, from, next) {
},
//离开守卫:通过路由规则,离开该组件时被调用
beforeRouteLeave (to, from, next) {
}