• Vue 中权限校验


    权限校验是指,当我们没有登录的时候,访问需要登录的页面,是无法直接进入的,需要登录后才会显示跳转内容。

    在Vue官网中叫导航守卫,官方参考:https://router.vuejs.org/zh/guide/advanced/navigation-guards.html

    正如其名,vue-router 提供的导航守卫主要用来通过跳转或取消的方式守卫导航。有多种机会植入路由导航过程中:全局的, 单个路由独享的, 或者组件级的。

    通过 router.beforeEach来注册全局守卫。

    这里需要引用router目录下的index.js里的VueRouter实例

    # router/index.js文件

    import Vue from "vue"; import VueRouter from "vue-router"; import login from "../views/Login" import home from "../components/Layout.vue" import homes from "../views/Home.vue" import dev from "../views/Dev.vue" Vue.use(VueRouter); // const originalPush = VueRouter.prototype.push // VueRouter.prototype.push = function push(location) { // return originalPush.call(this, location).catch(err => err) // }; export default new VueRouter({ routes:[ { path:"/",name:"/",component:login}, { path:"/home",name:"home", component:homes}, { path:"/tools",name:"tools",component:homes,children:[ {path:"/tools/dev",name:"dev",component:dev} ]} ] })

    创建一个新的js文件,引入router

    // 1、引入router,通过router实例实现页面验证token
    import Router from "../router/index.js"
    Router.beforeEach((to,from,next)=>{    // 使用beforEach-》to:目标路径,from当前路径,next是跳转方法
        const token = localStorage.getItem("token") // 这里我判断token是否存在
        if(token){
            next() //存在就允许跳转下一个路径
        }else{
            if(to.path !=="/"){  //to.path 可以获得跳转的路径
                next({path:"/"}) //next里可以传跳转路径
            }else{ 
                next()
            }
        }
    
    })
    

      

  • 相关阅读:
    解决mysql"Access denied for user'root'@'IP地址'"问题
    SpringMVC in IDEA开发实践
    Tomcat安装笔记(on Mac)
    mysql搭建及数据迁移教程
    remove-k-digits
    hdu 4691 Front compression
    STM32的FSMC总线复用调试笔记
    spring AOP 是如何一步一步被简化的
    hdu 2871 Memory Control(伸展树splay tree)
    [置顶] Objective-C ,/,ios,/iphone开发基础:协议(protocol)
  • 原文地址:https://www.cnblogs.com/TestingShare/p/14297303.html
Copyright © 2020-2023  润新知