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>是继续跳转或中断的方法。
    我们来看一下打印出的对象



  • 相关阅读:
    真正VC++.net笔记1系统时间的获取
    真正VC++.net笔记5MessageBox变MessageBoxA?
    Judge Online 系统流程设计
    杂谈1:事情因每个人的参与而不同
    ESX/ESXi 4.1 Update 1 or later 同步NTP
    iSCSI CHAP认证
    JSTL中c:set标签的要点和技巧
    JSTL 判断对象是否为空
    Smartmontools——linux磁盘检测工具
    ECMAScript 对象类型
  • 原文地址:https://www.cnblogs.com/Rivend/p/11984321.html
Copyright © 2011-2022 走看看