zoukankan      html  css  js  c++  java
  • vue router.beforeEach(),详解

    outer.beforeEach()一般用来做一些进入页面的限制。

    比如没有登录,

    就不能进入某些页面,只有登录了之后才有权限查看某些页面。。。说白了就是路由拦截。
    第一步 规定进入路由需不需要权限

     @/router/index.js
     import A from '@/components/a'
    {
         path: '/a',
         name: 'a',
         component:    A,
         meta : {                      //加一个自定义obj
                   requireAuth:true      //这个参数 true 代表需要登录才能进入A
         }
       },

    第二步 使用vuex整一个userId

    @/assets/store.js
    //使用vuex三步走
    import Vue from 'vue'
    import Vuex from 'vuex'
    Vue.use(Vuex)
    //这个理论来说
    const store = new Vuex.Store({
        state:{
            userId : ''
        }
    })
    export default store

    第三步 使用router.beforeEach()

    import store from '@/assets/store'   //把这个userId获取过来
    router.beforeEach((to,from,next)=>{
        if(to.meta.requireAuth){
            if(store.state.userId){
                next()
            }else{
                next({path:'/b'})
            }
        }else{
            next()
        }
    })

    第四步
    第三步这个/b路由其实就是登陆页面,
    当进入A页面之前,需要请求接口,获取一下是否有登陆过,然后把这个userId存在vuex的state里。
    当没有userId时,则在登陆之后,存一个userId到state里。然后就敲完收工

    全局钩子作用于所有路由,
    里面的参数
    <code>to</code>表示即将要进入的路由对象,
    <code>from</code>表示即将要离开的路由对象,
    <code>next</code>是继续跳转或中断的方法。
    我们来看一下打印出的对象



  • 相关阅读:
    Cypress自动化框架笔记
    SSH 用公钥免密登录,需要改文件权限
    python函数的可变参数 *和**
    Socket进程处理被中断的系统调用及Accept函数返回EINTR错误处理 (转)
    perror 与 strerror
    perror 函数
    strerror 函数
    getch ()函数 (来自百度百科)
    C语言运算符及其优先级汇总表口诀
    第四章
  • 原文地址:https://www.cnblogs.com/Rivend/p/11984321.html
Copyright © 2011-2022 走看看