Vue根据菜单json数据动态按需加载路由Vue-router
生活随笔
收集整理的這篇文章主要介紹了
Vue根据菜单json数据动态按需加载路由Vue-router
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
每個(gè)菜單項(xiàng)對(duì)應(yīng)一個(gè)頁(yè)面組件,根據(jù)菜單項(xiàng)動(dòng)態(tài)按需加載路由
路由配置的正確寫法:
/*router/index.js*/ import Vue from 'vue' import Router from 'vue-router' import url from './url' import store from '../store'Vue.use(Router)const router = new Router({// mode: 'history',routes: url,scrollBehavior (to, from, savedPosition) {return {x: 0,y: 0}} })router.beforeEach(({ meta, path, name }, from, next) => {let { auth = true } = metalet isAdmin = localStorage.getItem('admin')let isLogin = Boolean(isAdmin) // true已登錄, false未登錄if (auth && !isLogin && path !== '/login') {return next({ path: '/login' })}if (!auth && isLogin && path === '/login') {return next({ path: '/home' })}store.dispatch('CUR_MENU', name)next() })export default router 復(fù)制代碼/*router/url.js*/ import data from '../store/data.json' const Layout = () => import('@/pages/layout') const Login = () => import('@/pages/login') const NotFound = () => import('@/pages/notFound')function getChildrenPath () {let childrenPath = []for (let i in data) {let sub = data[i].subMenufor (let j in sub) {let component = () => import('@/pages' + sub[j].path + '/index.vue')const item = {path: sub[j].path,name: sub[j].name,component: component}childrenPath.push(item)}}return childrenPath }const url = [{path: '/',component: Layout,children: getChildrenPath() }, {path: '/login',meta: {auth: false},name: '登錄頁(yè)',component: Login }, {path: '*',name: '404頁(yè)',component: NotFound }]export default url 復(fù)制代碼重點(diǎn):let component = () => import('@/pages' + sub[j].path + '/index.vue')
動(dòng)態(tài)路徑寫法,不能省略/index.vue
省略的話不會(huì)報(bào)錯(cuò),頁(yè)面加載也正常,但是會(huì)彈警告:
參考: vue-router無(wú)法實(shí)現(xiàn)按需加載動(dòng)態(tài)組件,有什么替代方案可以解決這一需求呢?
轉(zhuǎn)載于:https://juejin.im/post/5a6a8f13518825732b1a0c9f
總結(jié)
以上是生活随笔為你收集整理的Vue根据菜单json数据动态按需加载路由Vue-router的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 苹果ios用js的Date()出现NaN
- 下一篇: html5倒计时秒杀怎么做,vue 设