【原创】Vue 路由其他

<router-link> 的 replace 属性

  • 作用:控制路由跳转时操作浏览器历史记录的模式。
  • 浏览器的历史记录有两种写入方式,分别是 pushreplacepush 是追加历史记录,replace 是替换当前记录,路由跳转时默认为 push
  • 开启 replace 模式:<router-link replace >News</router-link>

    浏览器历史记录默认是 push 模式,即一条堆在一条的上面。
    但浏览器还有 replace 模式,即替换到下面的数据。

编程式路由导航

编程式路由导航,即不借助 <router-link> 进行跳转的导航,让路由跳转更加灵活。

this.$router.push({
name:'detail',
params:{
id:666,
title:xxx
}
});

this.$router.replace({
name:'detail',
params:{
id:666,
title:xxx
}
});

this.$router.forward() // 前进
this.$router.back() // 后退
this.$router.go() // 向前或向后走几步

缓存路由组件

让不展示的路由组件保持挂载,不被销毁。

<keep-alive :include=['News','Message']>
<router-view></router-view>
</keep-alive>

注意,include 中写的内容是保持挂载的组件名称,如果不写 include,则所有组件都保持挂载,此处要设置组件名称。

两个路由组件特有的生命周期函数

用于捕获路由组件的激活状态。

  • actived 路由组件被激活时触发。
  • deactived 路由组件失活时触发。

路由守卫

对路由进行权限控制。

分类

  • 全局守卫
// 全局前置守卫
router.beforeEach((to, from, next)=>{
if(to.meta.isAuth){
if(localStorage.getItem('school') === 'xxx'){
next();
} else {
alert('您无权限查看');
}
} else {
 next();
}
})

// 全局后置守卫
router.afterEach((to, from)=>{
if(to.meta.title){
document.title = to.meta.title;
} else {
document.title = 'vue_test';
}
})
  • 独享守卫
    beforeEnter,写在单个路由配置中,参数与 beforeEach 相同。

    独享路由只有前置,没有后置。

  • 组件内守卫

// 进入守卫,通过路由规则进入
beforeRouteEnter(to, from, next) {

}

// 离开守卫,通过路由规则离开
beforeRouteLeave(to, from, next) {

}

history 模式与 hash 模式

http://localhost:8080/#/about 中的从 # 之后的内容都称作 hashhash 不会通过浏览器传递给服务器。

hash 模式

  • 地址中带着 # 号,不美观。
  • 以后地址在三方 APP 中分享,若 APP 校验严格,地址会被标记不合法。
  • 兼容性较好。

history 模式

  • 地址干净美观。
  • 兼容性比 hash 模式略差。
  • 应用部署上线时需后端人员支持,解决刷新页面服务端额404 问题。
点赞

发表回复

电子邮件地址不会被公开。必填项已用 * 标注