鍍金池/ 問答/HTML/ 請問vue在動態(tài)import加載頁面的時候,能否提前判斷頁面是否存在,如果不存在

請問vue在動態(tài)import加載頁面的時候,能否提前判斷頁面是否存在,如果不存在的話則引入404component。

有一個需求,就是根據(jù)后臺的給的menus,動態(tài)處理并加載到路由里去,但是因?yàn)椴藛问请S時會增加的,如果在沒有通知前端增加菜單的情況下,還需要展示菜單,但是對應(yīng)的相應(yīng)的component并沒有,如果沒有的話怎么才能判斷,并且加載404的頁面。
clipboard.png
代碼如下:

 component: _import(item.name.replace(/\./g,'/')) ? _import(item.name.replace(/\./g,'/')) : _import('errorPage/404'),

但是這個import如果找不到會直接報錯并不會執(zhí)行后面的,
之前有用以下方法測試

function matchVueFiles(name){
    const context = require.context('@/views',true,/\.vue$/);
    const keys = context.keys();
    return keys.indexOf(name);
}

但是該方法在線上不可以,因?yàn)榫€上沒有文件夾。所以該方法也不行,請求各位大神提供思路,解決辦法。

回答
編輯回答
下墜

可以再動態(tài)組件外面包裝一層,偽代碼。可能判斷邏輯不是這樣子的,思路是這樣子的

new Vue({
  // ...
  components: {
    'my-component': () => {
        return new Promise((resove, reject) => {
            var RemoteComponent = import('./my-async-component')
            var Component404 = import('./my-async-404-component')
            RemoteComponent.then(res => {
                resove(res)
            })
            
            RemoteComponent.catch(e => {
                Component404.then(res => {
                    resove(res)
                })
            })
        })
        
    }
  }
})
2018年1月21日 17:12
編輯回答
鐧簞噯

提供一種思路
建一個配置文件,配置現(xiàn)在已有的路由組件。在import之前先判斷item.name是否存在再決定加載哪一個。

//config.js
export default {components:['a', 'b']}
2017年10月30日 16:55