1. 程式人生 > 其它 >vue動態生成

vue動態生成

vue專案根據後端返回的路由動態生成並新增

RouterView程式碼:

<template>   <router-view></router-view> </template> RouterView只是用來中繼子頁面,才能讓頁面保持正常展示   如下圖是前端頁面檔案結構

這是後臺配置(URL就是路由路徑,也是和前端目錄路徑一致,因為我是直接用URL來對映前端元件)

訪問地址

buildRoutes(filterAsyncRoutes(後端返回的選單))生成的vue路由直接通過 addRoutes直接插入原有的路由裡
 1 // 載入檢視元件
2 function loadView(componentUrl) { 3 return resolve => require.ensure([], () => resolve(require('@/views' + componentUrl))) 4 } 5 6 // 遞迴構造路由 7 function buildRoutes(routes) { 8 return routes.map(route => { 9 let _route = {}; 10 let meta = { 11 title: route.name,
12 icon: route.icon, 13 }; 14 if (route.type == 1) { // 目錄 15 _route.component = route.parentId == 0 ? Layout : RouterView; 16 if (route.children && route.children[0]) { 17 _route.redirect = route.children[0].path; 18 }
19 } else if (route.type == 2) { // 選單 20 _route.component = loadView(route.url) 21 meta.actionButtonList = route.children || []; 22 } 23 return { 24 path: route.url, 25 name: route.code, 26 ..._route, 27 meta, 28 children: route.type == 1 ? buildRoutes(route.children || []) : [], // 只有目錄才去在構造children路由 29 } 30 }) 31 } 32 // 遞迴過濾掉有重定向卻沒有children的父級路由 33 function filterAsyncRoutes(routes) { 34 routes = routes.filter(d => { 35 return d.type != 1 || (d.children && d.children.length > 0) 36 }) 37 routes.forEach(route => { 38 if (route.children && route.children.length > 0) { 39 route.children = filterAsyncRoutes(route.children) 40 } 41 }) 42 return routes 43 }