Vue的路由守卫

全局路由守卫

import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter);

//路由表
const routes = [
  // 重定向定的是Home页面
  {
     
    path: "/",
    redirect: "/Home"
  },
  {
     
    path: "/Login",
    name: "Login",
    component: () => import("@/components/Login.vue") //对应的组件模板
  },
  {
     
    path: "/Home", //链接路径
    name: "Home",
    component: () => import("@/components/Home.vue") //对应的组件模板
  }
];
const router = new VueRouter({
     
  routes //路由表 必写的
});

//路由守卫
router.beforeEach((to, form, next) => {
     
  const nextRoute = ["Home"];
  // const auth = store.state.auth;
  // console.log(to.name);
  //未登录
  if (nextRoute.indexOf(to.name) >= 0) {
     
    //未登录
    // console.log(localStorage.getItem("name"));
    let name = localStorage.getItem("name");
    if (name == null) {
     
      router.push({
      name: "Login" });
    }
  } 
  // 已登录状态;当路由到login时,跳转至home
  if (to.name === "Login") {
     
    let name = localStorage.getItem("name");
    if (name != null) {
     
      router.push({
      name: "Home" });
    }
  }
  next();
});

//导出router
export default router;

组件守卫
beforeRouteEnter:进入组件时

beforeRouteUpdate:路由不变,传递的参数改变

beforeRouteLeave: 离开组件前

//进入该路由时判断如果有token 如果没有token,转到登录页面
 
     beforeRouteEnter:(to,from,next)=>{
     
          var tokens=getCookie("token");
           if(tokens.length>0){
     
               next()
           }else{
     
               alert("请您先登录")
               next('/login')
           }
          
    },

路由独享守卫

const router = new VueRouter({
     
      routes: [
        {
     
          path: '/foo',
          component: Foo,
          beforeEnter: (to, from, next) => {
      
            // 参数用法什么的都一样,调用顺序在全局前置守卫后面,所以不会被全局守卫覆盖
            // ...
          }
        }
      ]
    })

你可能感兴趣的:(Vue的路由守卫)