解決vue2.0路由跳轉未匹配相應路由而出現空白頁面的問題

在做項目的時候, 遇到前端控制路由跳轉, 但是當用戶手動輸入錯誤的路由,或者是一些不符合的路由的時候, 頁面就會出現一片空白, 也沒有任何報錯消息。

正常我們應該首先想到redirect去重定向路由, 可是測試發現http://localhost:3008/#/ 如果我們輸入的地址是醬紫的, 頁面並不能按照我們所想要實現的跳轉到首頁。

export default [
    {
        path: '/home',
        component: App,
        title: '運維管理',
        children: [
            {
                name: 'homeMain',
                path: '',
                title: '子頁面',
                component: require('../containers/homeMain/index')
            }
        ],
        extra: {
            inMenu: true,
            icon: 'el-icon-chain'
        }
    },
    {
        path: '/examine',
        component: App,
        title: '審覈',
        children: [
            {
                name: 'manger',
                path: '',
                title: '審覈',
                component: require('../containers/manger/index')
            }
        ],
        extra: {
            inMenu: true,
            icon: 'el-icon-chain'
        }
    },
    {
        path: '*',  //*號表示匹配任意內容
        component: App,
        title: '首頁',
        redirect: '/home',
        extra: {
            inMenu: false
        }
    }
];

那麼是不是還有其他解決方法呢?

哈哈,重點代碼如下:

    router.beforeEach((to, from, next) => {
        // 此處判斷條件我有看到其他人用to.matched.length ===0進行判斷, 具體的還有待進一步驗證,大體的思路就是這樣的
        if (to.fullPath === '/') { 
            from.name ? next({ name:from.name }) : next('/home');   
        } else {
            next(); //如果匹配到正確跳轉
        }
});
發佈了95 篇原創文章 · 獲贊 137 · 訪問量 31萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章