Vue根据菜单json数据动态按需加载路由Vue-router

1613040f104cf174.png

每个菜单项对应一个页面组件,根据菜单项动态按需加载路由

161304496186e365.png

路由配置的正确写法:

/*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 } = meta   
    let 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
/*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].subMenu     
        for (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: '登录页',   
        component: Login 
    }, 
    {   
        path: '*',   
        name: '404页',   
        component: NotFound 
    }
] 
export default url

重点:let component = () => import('@/pages' + sub[j].path + '/index.vue')

动态路径写法,不能省略/index.vue

省略的话不会报错,页面加载也正常,但是会弹警告:

16130497737b977a.png

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值