outer.beforeEach()通常用来作一些进入页面的限制。vue
好比没有登陆,vuex
就不能进入某些页面,只有登陆了以后才有权限查看某些页面。。。说白了就是路由拦截。
第一步 规定进入路由需不须要权限ui
@/router/index.js import A from '@/components/a' { path: '/a', name: 'a', component: A, meta : { //加一个自定义obj requireAuth:true //这个参数 true 表明须要登陆才能进入A } },
第二步 使用vuex整一个userIdspa
@/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()code
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里。而后就敲完收工component
全局钩子做用于全部路由,
里面的参数
<code>to</code>表示即将要进入的路由对象,
<code>from</code>表示即将要离开的路由对象,
<code>next</code>是继续跳转或中断的方法。 咱们来看一下打印出的对象