Dynamic Routing of Vue Development Example (15)

introduction

Vue is one of the most popular front-end frameworks. As a front-end developer, you should master it proficiently. If you plan to learn the development process of Vue, then come on, Brother Ming will take you to get started quickly and take you to fly!
Even if you are not a front-end developer, it is necessary to have a certain understanding of the front-end development process. No one is sure whether the company will let me do the front-end in the future. It does not take a lot of time to do some simple examples. It can improve your self-confidence and sense of accomplishment, so follow Brother Ming, there is nothing wrong, come on!

navigation

✪  General index of Vue development example directory ◄Previous article【14】Vue state management store ►Next article【16】Create tab page

overview

The scene is like this:
If I define 3 routes, namely '/index/menu1', '/index/menu2', '/index/menu3'
but the currently logged-in user is only '/index/menu1', '/ The authority of the two routes of index/menu2', if you follow the method in the previous chapter, you can directly enter the route address of '/index/menu3' in the browser to access, which is obviously wrong, so here we use dynamic routing .

review

Menu page Aside.vue

<template>
    <div style="height: 100%;">
        <el-menu background-color="#545c64" text-color="#ffffff"
                 active-text-color="#ffd04b" class="el-menu-vertical-demo"
                 router>
            <el-menu-item :index="item.path" v-for="item in menu_data" :key="item.name">
                <i :class="item.icon"></i>{
    
    {
    
    item.name}}
            </el-menu-item>
        </el-menu>
    </div>
</template>

<script>
    export default {
    
    
        name: "Aside",
        data(){
    
    
            return {
    
    
                menu_data:[
                    {
    
    
                        name:'一级菜单1',
                        icon:'el-icon-location',
                        path:'/index/menu1'
                    },
                    {
    
    
                        name:'一级菜单2',
                        icon:'el-icon-document',
                        path:'/index/menu2'
                    },
                    {
    
    
                        name:'一级菜单3',
                        icon:'el-icon-setting',
                        path:'/index/menu3'
                    }
                ]
            }
        }
    }
</script>

<style scoped>
    .el-menu-vertical-demo{
    
    
        height: 100%;

    }
</style>

Routing coderouter.js


import VueRouter from "vue-router"
import Index from "./components/Index";
import Aside from "./components/Aside";

const routes = [
    //一级路由
    {
    
    
        path: '/index',
        name: 'index',
        component: Index,
        redirect: '/index/Main',
        //路由嵌套
        children:[
            {
    
    path: '/index/Main',component: () => import('./components/Main.vue')},
            {
    
    path: '/index/menu1',component: () => import('./components/Main1.vue')},
            {
    
    path: '/index/menu2',component: () => import('./components/Main2.vue')},
            {
    
    path: '/index/menu3',component: () => import('./components/Main3.vue')}
        ]
    },
    {
    
    
        path: '/aside',
        name: 'aside',
        component: Aside
    }
]

const router = new VueRouter({
    
    
    mode:'history',
    routes
})

export  default router;

For the three sub-routes below, assuming that the backend only returns menu1 and menu2, that is, this route, we only need to create two dynamically.
insert image description here

Dynamically create menus

At present, the menu has been dynamically created, but the data is hard-coded. The mockjs in the previous chapter is used to simulate the data, and there is no menu3 in the dynamic data, so only the first two menus will be created.

  1. The original menu_data is returned using mockjs, which simulates the background query menu data return:
  • Define the object's /post/menuList path get request in mockjs
  • In addition to the original name, icon, and path, component is added to the return parameter, which is used to define the jump path.
Mock.mock('/post/menuList','get',function(){
    
    
    const menu_data = [
        {
    
    
            name:'一级菜单1',
            icon:'el-icon-location',
            path:'/index/menu1',
            component:'Main1'
        },
        {
    
    
            name:'一级菜单2',
            icon:'el-icon-document',
            path:'/index/menu2',
            component:'Main2'
        }
    ]

    return{
    
    
        menu_data
    }
});

  1. Modify in store.js

state add attribute menu_data

const state ={
    
    
    username: '明世隐',
    userState:0,
    menu_data:[]
}

Add method setMenuData in mutations

setMenuData(state,data){
    
    
   state.menu_data = data
}
  1. Use the method beforeEach in router.js to get the data and submit it to the store
  1. axios.get('/post/menuList') Get the menu data from the simulated background
  2. store.commit('setMenuData', res.data.menu_data) submit data
router.beforeEach((to, from, next)=>{
    
    
    next();
    axios.get('/post/menuList').then(res=>{
    
    
         store.commit('setMenuData',res.data.menu_data)
    });
})
  1. The attribute menu_data in data cannot be returned directly, it needs to be returned through computed, and the returned value is obtained from the store
computed:{
    
    
   menu_data:{
    
    
       get(){
    
    
           return this.$store.state.menu_data
       }
    }
}

At this time, the complete code of Aside.vue is as follows:

<template>
    <div style="height: 100%;">
        <el-menu background-color="#545c64" text-color="#ffffff"
                 active-text-color="#ffd04b" class="el-menu-vertical-demo"
                 router>
            <el-menu-item :index="item.path" v-for="item in menu_data" :key="item.name">
                <i :class="item.icon"></i>{
    
    {
    
    item.name}}
            </el-menu-item>
        </el-menu>
    </div>
</template>

<script>
    export default {
    
    
        name: "Aside",
        data(){
    
    
            return {
    
    }
        },
        computed:{
    
    
            menu_data:{
    
    
               get(){
    
    
                   return this.$store.state.menu_data
               }
            }
        }

    }
</script>

<style scoped>
    .el-menu-vertical-demo{
    
    
        height: 100%;

    }
</style>
  1. page effect
    insert image description here

At this time, there are indeed only two menus in the menu. Clicking on the menu can also access the corresponding routes menu1 and menu2, but when we enter menu3 in the address bar, we can also access it. This is obviously wrong, because our route is statically written. Yes, it is definitely unreasonable here, so it needs to be modified dynamically.

insert image description here

Create routes based on menu data

Let’s take a look at our current way of writing the route
insert image description here
. In view of the above situation, can we consider adding the route dynamically to the data obtained through the menu instead of writing it to death directly.

  1. First delete these 3 routing codes

insert image description here
2. Create a method buildRouter to add dynamic routing in router.js

let oRouters = router.options.routes;
const buildRouter = ()=>{
    
    
    let data = store.state.menu_data;
    data.forEach(item=>{
    
    
        let new_router = {
    
    
            path:item.path,
            component:() => import('./components/'+item.component+'.vue')
        }
        oRouters[0].children.push(new_router);
    })
    router.addRoutes(oRouters)
}
  1. Call this function while creating the dynamic menu

Modify the beforeEach before calling buildRouter

router.beforeEach((to, from, next)=>{
    
    
    next();
    axios.get('/post/menuList').then(res=>{
    
    
         store.commit('setMenuData',res.data.menu_data);

        //动态创建路由
        buildRouter();
    });

})
  1. test

menu1 menu2 test click normal

insert image description here

Enter menu3 in the address bar, the page cannot be displayed because there is no such route

insert image description here

Add the route loaded tag, save every click on the menu to load

  1. Add the attribute isLoadRoute to false in the state of store.js
    insert image description here

  2. Add update method in mutations

setLoadRoute(state,data){
    
    
    state.isLoadRoute = data
}
  1. Add the router.beforeEach of the route in router.js with a slight modification
router.beforeEach((to, from, next)=>{
    
    
    //判断路由是否已经加载过
    let isLoadRoute = store.state.isLoadRoute;
    if(!isLoadRoute){
    
    
        axios.get('/post/menuList').then(res=>{
    
    
            store.commit('setMenuData',res.data.menu_data);

            //动态创建路由
            buildRouter();
            //设置已经加载过的标记
            store.commit("setLoadRoute",true);
        });
    }
    next();
})

At this time, clicking the menu will not load repeatedly.

summary

This section summarizes "Dynamic Routing", I hope it can be helpful to everyone, please help [Like] + [Favorite] + [Punch in the Comment Area] If you are interested in learning Java and front-end with Brother Xiaoming, [Follow a wave] Don't get lost.
Please go to the bottom of the article to help [One-click three links] Thank you!

insert image description here

navigation

✪  General index of Vue development example directory ◄Previous article【14】Vue state management store ►Next article【16】Create tab page

Popular column recommendation

【1】Java mini-games (Tetris, Plants vs. Zombies, etc.)
2】JavaWeb project combat (library management, dormitory management, etc.)
【3】JavaScript wonderful examples (aircraft wars, verification codes, etc.)
200 cases
[5] Learn Java from zero, learn Java with fun
[6] IDEA from zero to proficient
insert image description here

Guess you like

Origin blog.csdn.net/dkm123456/article/details/124480454