1. 程式人生 > 實用技巧 >vue 路由跳轉未匹配相應路由後,出現空白頁面,指向404頁面

vue 路由跳轉未匹配相應路由後,出現空白頁面,指向404頁面

1、比如我是寫在根目錄的:

2、點選跳轉到沒許可權的路由(因為沒許可權,該路由找不到,顯示空白頁):

3、路由守衛如下:

router.beforeEach((to, from, next) => {
  const hasToken = getToken();
  // console.log(hasToken)
  // console.log('length=' + getRouter.length)
  if(!getObjArr('router')) {
    getRouter = []
    // console.log(getRouter)
  }
  // console.log(getRouter);  // 後端路由
if (getRouter.length === 0) { // 不加這個判斷,路由會陷入死迴圈 if (!getObjArr('router')) { if (to.path === '/login' || from.path === '/dashboard' || from.path === '/') { // 若使用者已經登入,則重定向到主頁 // || from.fullPath === '/' || from.fullPath === '/dashboard' } else {
      //獲取路由介面 getMenu().then(res => { var conet = [] var head = [] res.menu.forEach((items, index) => { items.meta = { title: items.name, icon: 'dashboard' // items.icon } if (items.parentId) { conet.push(items) } else { items.children = [] head.push(items) } }) head.forEach((items, index) => { conet.forEach((item, index) => { if (items.id === item.parentId) { items.children.push(item) } }) }) getRouter = head saveObjArr('router', getRouter) routerGo(to, next) // location.reload() }).catch(() => { }) } } else { // 從localStorage拿到了路由 getRouter = getObjArr('router') // 拿到路由 routerGo(to, next) } } else { next() }

4、此時無許可權路由跳轉為空白頁,需要新增如下(此時未匹配到的路由,會跳轉到404頁面):

} else if(to.matched.length === 0) {
    from.path? next({ path: '*', redirect: '/404', hidden: true }) : next('/');  //404頁面內容可以自定義
  } else {
    next()
  }

注:每個人的路由守衛頁面、路由寫法等都不一樣,所以該部落格僅供參考!