vue路由钩子方法

index.js配置:

{
    path:'home',
    component:'home',    
    meta:{
        index:1,
        login:true,
        title:'home'
    }
}

main.js

//进入路由前
router.beforeEach( ( to,from,next )=>{  
    if( to.meta.login ){  //要进入的组件需要先进行登录
        console.log(to);
        next('/login');  //如果没有登录就重定向到登录页
或者        
next({
        path: '/login',
        query: {redirect: to.fullPath}  // 将跳转的路由path作为参数,登录成功后跳转到该路由
----------------
但是事实是登录的时候大多数时候并不进行跳转,所以这里需要在login跳转的路径中再加一段:
if(this.$route.query.redirect){
//     let redirect = decodeURIComponent(this.$route.query.redirect);
       let redirect = this.$route.query.redirect;
       this.$router.push(redirect);
}else{
       this.$router.push('/');
 }
----------------
      })
    }
else{
        next();  //已经登录,就渲染要进入的组件内容

    }
} )

//进入路由后
router.afterEach( ( to,from )=>{  //这里不需要next了,因为已经进入了
    if( to.meta.title ){  //切换不同的组件,页面title改变为对应的值
        window.document.title=to.meta.title;
    }else{
        window.document.title='myTitle';  //注意这里document前面需要加上window,否则访问不到
    }
} )

你可能感兴趣的:(vue路由钩子方法)