vue-404页面配置
1 SPA的404路由配置
SPA路由表固定:
路由表中添加一个路径为404
的路由,同时在路由表的最底部配置一个路径为*
的路由,重定向至404路由即可。
// router.js export default new Router({ mode: 'history', routes: [ // ... { name: '404', path: '/404', component: () => import('@/views/notFound.vue') }, { path: '*', // 此处需特别注意至于最底部 redirect: '/404' } ], })
路由表动态生成的情况
路由表是动态生成的情况下,也就是说路由表分为两部分,一部分为基础路由表,另一部分是需要根据用户的权限信息动态生成的路由表。
本项目中动态生成路由采用vue-router自带的addRoutes方法,该方法是会将新的路由规则在原路由表数组的尾部注入的。由于任意匹配重定向至404页面的规则必须至于路由表的最底部,所以此处我将重定向至404页面的规则抽出,在动态路由注入后,再注入重定向规则,以确保该规则至于路由表最底部。
// router.js export default new Router({ mode: 'history', routes: [ // ... { name: '404', path: '/404', component: () => import('@/views/notFound.vue') }, // ...other codes ], })
// notFoundRouterMap.js export default [ { path: '*', redirect: '/404' } ]
// main.js //...other codes router.beforeEach((to, from, next) => { new Promise((resolve, reject) => { if (getCookie(tokenName)) { if (!getInfo()) { Promise.all([store.dispatch('getBasicInfo'), store.dispatch('getUserDetail')]).then(res => { store.dispatch('GenerateRoutes', { roles }).then(() => { // 根据用户权限生成可访问的路由表 router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表 router.addRoutes(NotFoundRouterMap) // 添加404及重定向路由规则 resolve({ ...to, replace: true }) // 重新加载一次路由,让路由表更新成功后走下面else的判断 }) }) } else { // ...other codes } } else { window.location.href = '/login.html' } }).then(res => { if (res) { next(res) } else { next() } }).catch(err => { new Error(err) next(false) })
多页应用的404路由配置
多页应用区别于SPA的不同点是每个页面有自己的一套路由,并且每个页面可能有自己的一套404页面风格,当然也可能没有。这时候,就不能再采用动态添加路由规则的方法了。
我采用的方案是在全局导航守卫beforeEach中对路由匹配的情况进行判断,这时候就需要用到vue导航守卫中的matched
数组了。如果没有一个匹配上的,那么就重定向至404页面。当然,这个404页面也单独设置为一个页面。
// permission.js //...other codes router.beforeEach((to, from, next) => { new Promise((resolve, reject) => { // ...other codes }).then(res => { if (!to.matched.length) { window.location = '/error.html#/404' return } if (res) { next(res) } else { next() } }).catch(err => { new Error(err) next(false) })
这个方案就允许每个页面有自己的404页面路由规则,并且为没有配置404页面的路由统一配置了默认的404页面,感觉还是比较友好的。