vue require动态路径图片报错_Vue 动态生成路由结构
生活随笔
收集整理的這篇文章主要介紹了
vue require动态路径图片报错_Vue 动态生成路由结构
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
通常我們比較常用的vue組件加載方式就是通過import引入文件,如:路由懶加載 、靜態的import。
一般情況下還是推薦使用import方式引入的,因為這更容易從Tree_shaking 及一些分析工具中受益。
在一些比較特殊的場景,比如:
需要根據后臺的菜單配置, 動態生成Vue路由。
假如后臺返回了以下JSON數據結構
[ { "alwaysShow":true, "children":[ { "alwaysShow":false, "component":"OA/AskForLeaveManagement/AskForLeaveManagement", "hidden":false, "meta":{ "icon":"", "id":2004, "title":"請假管理" }, "name":"AskForLeaveManagement", "path":"askForLeaveManagement", "redirect":"" }, { "alwaysShow":false, "children":[ ], "component":"OA/WorkOvertimeManagement/WorkOvertimeManagement", "hidden":false, "meta":{ "icon":"", "id":3687, "title":"加班管理" }, "name":"WorkOvertimeManagement", "path":"workOvertimeManagement", "redirect":"" }, ], "component":"Layout", "hidden":false, "meta":{ "icon":"dashboard", "id":2001, "title":"辦公管理" }, "name":"Oa", "path":"/oa", "redirect":"noRedirect" }, { "alwaysShow":false, "children":[ ], "component":"Layout", "hidden":true, "meta":{ "icon":"", "id":3618, "title":"首頁" }, "name":"Dashboard", "path":"/dashboard", "redirect":"" }]一般vue路由會類似這樣定義
{ path: '/redirect', component: Layout, hidden: true, children: [ { path: '/redirect/:path*', component: () => import('@/views/redirect/index'), }, ], }, { path: '/login', component: () => import('@/views/login/index'), hidden: true, }, { path: '/auth-redirect', component: () => import('@/views/login/auth-redirect'), hidden: true, },從JSON數據結構轉換到vue路由定義,我們只需要進行遞歸處理就好 。
但這里面我們需要重點關注 component的實現
component:()=>import('@/views/redirect/index'),假如我們繼續通過import 引入組件的方式,在我們進行遞歸處理進行動態賦值時,比如
component:()=>import('@/views/' + path ),會發現 import 其實是不支持動態變量的,所以我們通過這種方式是無法正確找到路由的
require(AMD版本)
針對上面使用 import 出現無法正確找到路由的情況,我們可以通過這種方式處理。
定義loadComponent函數,將后臺返回內容處理后, 再賦值給 component
const loadComponent = (path) => { // 路由懶加載 return (resolve) => require(['../../components' + path], resolve)}假如想加載不同文件夾下的vue文件, 我們需要聲明文件目錄的前綴, 不然也會報錯的
export const loadViews = (view) => { // 路由懶加載 return (resolve) => require(['../../views/' + view], resolve)}export const loadComponents = (path) => { // 路由懶加載 return (resolve) => require(['../../components' + path], resolve)}通過這種方式改造后,Vue路由可以完全的通過后臺進行控制, 如: 公用組件的參數設置、動態設置按鈕關聯組件等等
假如想通過某個按鈕點擊后加載某個vue組件, 可以封裝上面的方法, 大致如下
getComponents(value) { return new Promise((r, j) => { const url = value.replace('', '/') if (url.includes('components')) { const path = url.replace('components', '') require(['@/components' + path], function(v) { r(v) }).catch(e => { console.log('error', e) j(new Error(`無法找到組件,請確認地址是否正確`)) }) } else { require(['@/views/' + url], function(v) { r(v) }).catch(e => { console.log('error', e) j(new Error(`無法找到組件,請確認地址是否正確`)) }) } }) },有哪里寫的不好或者想討論的可以在下方 評論區跟我討論噢
總結
以上是生活随笔為你收集整理的vue require动态路径图片报错_Vue 动态生成路由结构的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 余额宝有钱但是无法出?
- 下一篇: 闪银科技是什么贷款