26、router.beforeEach路由拦截

为了防止用户未登录直接修改路径来访问页面,解决办法:

在main.js文件中加入以下代码:

// 路由拦截
router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth) { //判断该路由是否需要登录
    if (store.state.Token) { //vuex获取当前token是否存在
      next();
    } else {
      Message({
        showClose: true,
        message: '请先登录!',
        type: "warning"
      });
      next({
        path: '/login',
        query: { redirect: to.fullPath } //将跳转的路由path作为参数,登录成功后跳转该路由
      })
    }
  } else { //无需登录直接跳转页面
    next();
  }
})

在需要拦截的路由中添加:

posted @ 2019-07-24 16:12  要什么自行车y  阅读(2279)  评论(0编辑  收藏  举报