今天做新項目發現,當通路的頁面路由不存在的時候,頁面顯示一片空白,需要新增一個404錯誤頁面,那麼怎麼才能跳轉到這個404頁面呢
方法:在路由頁面,一般檔案名為index.js ,在最後添加一個path:*; 優先級從上到下查找路由,都沒有的時候全部指向 404頁面 ,代碼如下:
我把index.js檔案放在router檔案夾下;一般也會放在page檔案下或者views檔案夾有這麼一個index.js檔案
優點:簡單、友善;
缺點:如果項目中添加了判斷token失效跳出登入然後記住目前頁面,登入時候自動跳轉到上次token失效的頁面,就會有問題,如果故意輸入不存在的路由就會在404,失效退出然後登陸後就會自動跳到這個404頁面,那樣就尴尬了;如果沒有這個功能,用上述方法還是比較好使的
解決方法:在index.js檔案中注釋剛剛加入的path:* 這些東西
在router.beforeEach 裡面使用 to.matched 比對出的路由個數來作為判斷條件,比對不到路由就跳轉到404頁面,代碼如下
pemmision.js
代碼如下:
import router from './router'
import { getCookie } from './utils/auth'
// 通過beforeEach鈎子來判斷使用者是否登陸過 有無token
const whiteList = ['/login'] // 不重定向白名單
// const userInfo = getUserInfo()
router.beforeEach((to, from, next) => {
console.log(to.matched)
// 判斷是否有登入過
if (getCookie('userId_dev')) {
// 如果包含userId_dev 從登入頁面跳轉 直接跳轉到首頁 /
if (to.path === '/login') {
next()
} else {
if (to.matched.length === 0) {
next('/404') // 判斷此跳轉路由的來源路由是否存在,存在的情況跳轉到來源路由,否則跳轉到404頁面
}
next() // 如果比對到正确跳轉
}
// 沒有登入
} else {
if (whiteList.indexOf(to.path) !== -1) {
next()
} else {
// 還沒有登入過 則跳轉到登入界面
// next('/login')
if (to.path.slice(1) !== '') {
if (to.matched.length === 0) {
router.push({
path: '/login'
})
} else {
router.push({
path: '/login',
query: {
redirect: to.path.slice(1)
}
})
}
} else {
router.push({
path: '/login'
})
}
}
}
})