Vue路由拦截

4,175 阅读1分钟

这里主要是总结一下vue路由拦截的用法,具体如下:

1、首先对原有路由文件进行一下修改。(这里只是问了区分出来,清晰一些)
新建router.js来存放页面路由:

import Home from '@/components/Home'
import Login from '@/components/Login'
import About from '@/components/About'

export const RouterPath = [
    {
        path:'/',
        redirect: '/Home'
    },
    {
        path:'/Home',
        name:'Home',
        meta: { title: "首页" },
        component: Home
    },
    {
        path: '/Login',
        meta:{title:'登录'},
        name: 'Login',
        component: Login
    },
    {
        path: '/About/:id',
        meta: { title: '关于我们' },
        name: 'About',
        component: About
    },
];

2、修改原有路由文件index.js,改为
import Vue from 'vue'
import Router from 'vue-router'
import { RouterPath } from './router'

Vue.use(Router)

const router = new Router({
  mode: 'history', //去掉url中的#
  routes: RouterPath
})

export default router;

/** 
 * to表示即将进入的页面路由,
 * from表示当前导航正要离开的路由
 * next: Function:执行效果依赖 next 方法的调用参数。
 * next(): 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。
 * next(false): 中断当前的导航。如果浏览器的 URL 改变了(可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。
 * next('/') 或者 next({ path: '/' }): 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。
 * next(error): (2.4.0+) 如果传入 next 的参数是一个 Error 实例,则导航会被终止且该错误会被传递给 router.onError() 注册过的回调。
*/
router.beforeEach((to, from, next) => {
  //console.log(to);
  //console.log(from);
  /* 路由发生变化修改页面title */
  if (to.meta.title) {
    document.title = to.meta.title
  };
  const isLogin = sessionStorage.getItem("sessiontoken");
  if (isLogin){
    next();
  }else{
    if (to.fullPath == "/Login") {
      next();
    }else{
      next({path: '/Login'})
    };
  };
})

3、在main.js中注入路由,如下:
import router from './router'

new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})