您的位置:首页 > Web前端 > Vue.js

Vue Router导航守卫

2019-03-23 13:10 162 查看

导航守卫

Vue Router进阶中导航守卫还是蛮重要的,所以在这里根据师父教的和自己的理解做了一些总结

vue-router 提供的导航守卫主要用来通过跳转或取消的方式守卫导航。有多种机会植入路由导航过程中:全局的, 单个路由独享的, 或者组件级的。

1. beforeEach 全局前置守卫(进入下一页之前)

具体代码:

import router from './router'
router.beforeEach(to,from,next) => {
if(to.path !== '/'){
if(localStorage.getItem('access_token')){
next();
}else{
next({
replace: true,
name: 'Login'
})
}
}else{
next();
}
}

每个守卫方法接收三个参数:

  • to: 即将要进入的目标 路由对象。
  • from:当前导航正要离开的路由。
  • next:一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。 next()::进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。
  • next(false):中断当前的导航。如果浏览器的 URL 改变了 (可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。
  • next(’/’) 或者 next({ path: ‘/’ }):跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。你可以向 next 传递任意位置对象,且允许设置诸如 replace: true、name: ‘home’ 之类的选项以及任何用在 router-link 的 to prop 或 router.push 中的选项。
  • next(error):(2.4.0+) 如果传入 next 的参数是一个 Error 实例,则导航会被终止且该错误会被传递给 router.onError() 注册过的回调。

确保要调用 next 方法,否则钩子就不会被 resolved。

2. beforeResolve 全局解析守卫 (导航已经准备好但还未跳转到页面)

全局解析守卫和 router.beforeEach 类似,区别是在导航被确认之前,同时在所有组件内守卫和异步路由组件被解析之后,解析守卫就被调用。

router.beforeResolve(to,from,next){
//...
}

3. afterEach 全局后置钩子(进入下一页之后)

使用全局后置钩子时,没有调用next方法,因为这些钩子不会接受 next

router.afterEach(to,from){
//...
}

4. beforeEnter 路由独享守卫

可以直接在路由配置上定义,只能由该路由自己使用

export default new Router({
routers: [
{
path: '/',
name: 'Login',
component: Login,
beforeEnter: (to,from,next) => {
//...
}
}
]
})

5. 组件内的守卫

  • 5.1 beforeRouteEnter (即将进入组件)

index.js

{
path: '/new_content',
name: 'NewContent',
component: NewContent,
alias: '/new_contents'//设置别名
meta: { //动态设置meta标签和title标签
title: '新闻详情',
keywords: '新闻详情'
},
props: route => ({ //接受路由参数
name: route.query.name
})
}

new_content.vue

//即将进入组件之前
router.beforeRouteEnter(to,from,next){
console.log(to.meta.title);
window.document.title = to.mata.title; //修改页面的title标题
//html页面显示:
//<title></title>
//<meta type="keywords" content=" " />
next(
//beforePouteEnter不能获取组件实例this,但是可以通过传一个回调给 next来访问组件实例
vm => {
//通过vm访问组件实例
console.log(vm);
console.log(vm.name);
}
)
}
  • 5.2 beforeRouteLeave (即将离开组件,进入另一个组件)

new_content.vue

router.beforeRouteLeave(to,from,next){
//beforePouteLeave可以获取组件实例this,但是不支持回调
var masg = confirm('是否要离开组件');
if(msg){
next();
}else{
next(false);
}
}
  • 5.3 beforeRouteUpdate (监听路由参数变化(例如:新闻详情页面,点击其他的新闻信息))

new_content.vue

router.beforeRouteUpdate(to,from,next){
//beforeUpdate可以获取组件实例this,但是不支持回调
console.log(to);
console.log(to.query.name);
next(
//获取列表信息
//this.getList()
);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: