Vue的路由守卫
发布日期:2021-05-08 02:23:16 浏览次数:20 分类:精选文章

本文共 1660 字,大约阅读时间需要 5 分钟。

全局路由守卫

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();});//导出routerexport 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的生命周期函数
下一篇:vue中data为什么必须是一个函数

发表评论

最新留言

表示我来过!
[***.240.166.169]2025年03月25日 13时55分38秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章