博主菜鸡,有错请各位指出
路由守卫
router.beforeEach
:全局前置守卫。
router.beforeResolve
:全局解析守卫。
router.afterEach
:全局后置钩子。
组件守卫
beforeRouteEnter
beforeRouteUpdate
beforeRouteLeave
路由独享守卫
beforeEnter
总结
导航被触发。
在失活的组件里调用 beforeRouteLeave
守卫。
调用全局的 beforeEach
守卫。
在重用的组件里调用 beforeRouteUpdate
守卫 (2.2+)。
在路由配置里调用 beforeEnter
。
解析异步路由组件。
在被激活的组件里调用 beforeRouteEnter
。
调用全局的 beforeResolve
守卫 (2.5+)。
导航被确认。
调用全局的 afterEach
钩子。
触发 DOM 更新。
调用 beforeRouteEnter
守卫中传给 next 的回调函数,创建好的组件实例会作为回调函数的参数传入。
router.beforeEach((to,from,next)=>{})
router.beforeEach((to,from,next)=>{if(to.path == '/login' || to.path == '/register'){next();}else{alert('您还没有登录,请先登录');next('/login');}
})
router.afterEach((to,from)=>{})
只有两个参数,to:进入到哪个路由去,from:从哪个路由离。
到达组件时
beforeRouteEnter:(to,from,next)=>{}
离开组件时
beforeRouteLeave:(to,from,next)=>{}
点击其他组件时,判断是否确认离开。确认执行next();取消执行next(false),留在当前页面。
beforeRouteLeave:(to,from,next)=>{if(confirm("确定离开此页面吗?") == true){next();}else{next(false);}}
组件更新时
beforeRouteUpdate:(to,from,next)=>{}
beforeRouteUpdate (to, from, next) {console.log('路由更新之前:从to获取参数', to.params, '从this.$route获取参数', this.$route.params)next()console.log('路由更新之后:从to获取参数', to.params, '从this.$route获取参数', this.$route.params)},
beforeEnter:(to,from,next)=>{}
写进其中一个路由对象中,只在这个路由下起作用。
{path:"/login",name:"login",component:"/login",beforeEnter:(to,from,next)=>{next('/login')}
}
进度条结束
NProgress.done()
index.js
import router from './routers'
import store from '@/store'
import Config from '@/settings'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'// progress bar style
import { getToken } from '@/utils/auth' // getToken from cookie
import { buildMenus } from '@/api/system/menu'
import { filterAsyncRouter } from '@/store/modules/permission'NProgress.configure({ showSpinner: false })// NProgress Configurationconst whiteList = ['/login']// no redirect whitelist
router.beforeEach((to, from, next) => {if (to.meta.title) {//假如路由组件挂载的时候有写title,则是title-项目名称,Config.title配置了项目名称document.title = to.meta.title + ' - ' + Config.title}NProgress.start()//开启进度条if (getToken()) {if (to.path === '/login') {// 已登录且要跳转的页面是登录页,此时不能进登录页next({ path: '/' })//修改路由为loginNProgress.done()} else {//这块Vuex没看懂if (store.getters.roles.length === 0) { // 判断当前用户是否已拉取完user_info信息store.dispatch('GetInfo').then(() => { // 拉取user_info// 动态路由,拉取菜单loadMenus(next, to)}).catch(() => {store.dispatch('LogOut').then(() => {location.reload() // 为了重新实例化vue-router对象 避免bug})})// 登录时未拉取 菜单,在此处拉取} else if (store.getters.loadMenus) {// 修改成false,防止死循环store.dispatch('updateLoadMenus')loadMenus(next, to)} else {next()//不满足其他条件,放行}}} else {/* has no token*/if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单,直接进入next()} else {next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页NProgress.done()}}
})export const loadMenus = (next, to) => {buildMenus().then(res => {const sdata = JSON.parse(JSON.stringify(res))const rdata = JSON.parse(JSON.stringify(res))const sidebarRoutes = filterAsyncRouter(sdata)const rewriteRoutes = filterAsyncRouter(rdata, false, true)rewriteRoutes.push({ path: '*', redirect: '/404', hidden: true })store.dispatch('GenerateRoutes', rewriteRoutes).then(() => { // 存储路由router.addRoutes(rewriteRoutes) // 动态添加可访问路由表next({ ...to, replace: true })})store.dispatch('SetSidebarRouters', sidebarRoutes)})
}
permission.js
import { constantRouterMap } from '@/router/routers'
import Layout from '@/layout/index'
import ParentView from '@/components/ParentView'const permission = {state: {routers: constantRouterMap,addRouters: [],sidebarRouters: []},mutations: {SET_ROUTERS: (state, routers) => {state.addRouters = routersstate.routers = constantRouterMap.concat(routers)},SET_SIDEBAR_ROUTERS: (state, routers) => {state.sidebarRouters = constantRouterMap.concat(routers)}},actions: {GenerateRoutes({ commit }, asyncRouter) {commit('SET_ROUTERS', asyncRouter)},SetSidebarRouters({ commit }, sidebarRouter) {commit('SET_SIDEBAR_ROUTERS', sidebarRouter)}}
}export const filterAsyncRouter = (routers, lastRouter = false, type = false) => { // 遍历后台传来的路由字符串,转换为组件对象return routers.filter(router => {if (type && router.children) {router.children = filterChildren(router.children)}if (router.component) {if (router.component === 'Layout') { // Layout组件特殊处理router.component = Layout} else if (router.component === 'ParentView') {router.component = ParentView} else {const component = router.componentrouter.component = loadView(component)}}if (router.children != null && router.children && router.children.length) {router.children = filterAsyncRouter(router.children, router, type)} else {delete router['children']delete router['redirect']}return true})
}function filterChildren(childrenMap, lastRouter = false) {var children = []childrenMap.forEach((el, index) => {if (el.children && el.children.length) {if (el.component === 'ParentView') {el.children.forEach(c => {c.path = el.path + '/' + c.pathif (c.children && c.children.length) {children = children.concat(filterChildren(c.children, c))return}children.push(c)})return}}if (lastRouter) {el.path = lastRouter.path + '/' + el.path}children = children.concat(el)})return children
}export const loadView = (view) => {return (resolve) => require([`@/views/${view}`], resolve)
}
export default permission