Vue3 Beginner's Notes Six - Implementing Page Routing Function

This series of notes will focus on how to set up a project using Vue3 and interact with the backend API. It won’t introduce the basic features of Vue. For the basic features of Vue, you can refer to this video [Get Started with Vue in Four Hours](https://www.bilibili.com/video/BV12J411m7MG/?spm_id_from=333.337.search - card.all.click&vd_source=55550879a421ab9d1e89e4ff47481a4d). I got started with Vue by watching this video and thought it was pretty good.

Code address: [https://github.com/yexia553/vue_study/tree/%E9%85%8D%E7%BD%AEvue - router/vue3 - notes](https://github.com/yexia553/vue_study/tree/%E9%85%8D%E7%BD%AEvue - router/vue3 - notes)

Improving Page Routing

In fact, we have already configured page routing in [Vue3 Beginner’s Notes Two - Configuring Routes with vue - router](Vue3入门笔记二—-使用vue - router配置路由.md). However, the function was very simple, with only a main route used to direct the browser to the home page. But in actual development, there surely won’t be just one page to display. Otherwise, there would be no need for the routing function.

Which Routes Do We Need?

Let’s take another look at the buttons in the left - hand menu bar we had before, as shown in the figure below.
vue3 - router - demo
We can see that there are two buttons, “Home” and “Other”. Behind these two buttons actually correspond to two routes.
Although there won’t be just these two buttons in an actual project, the implementation is similar. So we’ll use these two as examples.

Modifying the Routing Configuration

As mentioned in Vue3 Beginner’s Notes - Configuring Routes with vue - router, the routing configuration is placed in the src/router/index.js file. We need to add the “Home” and “Other” routes mentioned above in it. After adding, the content of the file is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import { createRouter, createWebHashHistory } from 'vue-router'


const routes = [
{
path: '/',
name: 'main',
redirect: '/home', // Used for redirection,
component: () => import('../views/Main.vue'),
children: [
{
path: '/home',
name: 'home',
component: () => import('../views/home/Home.vue'),
},
{
path: '/other',
name: 'other',
component: () => import('../views/other/Other.vue'),
},
]
},
]

const router = createRouter({
history: createWebHashHistory(),
routes
})

export default router
```
In the above code, the 8th line `redirect: '/home' ` is used for redirection. When the route points to "/main", it will be redirected to "/home" because the /main route is actually only needed when we write code to encapsulate components, and the people visiting the page don't need to know about it.

The code also references the Other.vue file, which we don't have yet. We need to create it. Create an Other.vue file in the src/views/other/ directory with the following content:
```html
<template>
Other
</template>

Referencing Routes in Main.vue

We’ve determined which routes are needed above and added the corresponding routes in router/index.js, but we haven’t actually applied them yet. Now let’s do it.

As mentioned before, /src/Main.vue is a common component for all pages, which means all pages are its sub - components (this statement is not entirely accurate because the concept of components doesn’t really apply to pages, but it’s roughly this idea). Main.vue divides the entire page into three parts: the left - hand common menu bar, the top common header part, and the main display part, that is, the content inside the el - main tag in the template of Main.vue, as follows:

<template>
    <div class="common - layout">
        <el - container>
            <el - aside width="180px">
                <common - aside></common - aside>
            </el - aside>
            <el - container>
                <el - header>
                    <common - header></common - header>
                </el - header>
                <el - main>
                    Main
                </el - main>
            </el - container>
        </el - container>
    </div>
</template>

Now the el - main tag contains just a string “Main”. We need to replace this “Main” with <router - view></router - view>, so that the two routes added before can be applied.
In fact, we did the same thing in App.vue. You can check the code in App.vue to understand. The principle is the same.

Adding a Jump Function to the Left - Hand Menu Bar

We’ve added two routes and their corresponding pages above, and also applied the routes in Main.vue. But the routes won’t jump by themselves. They need to be triggered manually. Usually, it’s by clicking a button on the page. In our case, it’s by clicking the left - hand menu bar. Now let’s implement this function.

In fact, it’s very simple to implement. Just bind a click event to each menu item. The function triggered by this event is to make the browser jump to the corresponding page. See the following code for the specific implementation.

After modification, the content of src/components/CommonAside.vue is as follows:

<template>
    <el - aside>
        <el - menu class="el - menu - vertical - demo" background - color="#545c64" text - color="#fff" :collapse - transition="false"
            active - text - color="#ffd04b">
            <h3>Backend Management</h3>
            <el - menu - item :index="item.path + ''" v - for="item in list" :key="item.label" @click="handleClick(item)">
                <component class="icons" :is="item.icon"></component>
                <span>{{ item.label }}</span>
            </el - menu - item>
        </el - menu>
    </el - aside>
</template>

<script>
import { useRouter } from 'vue-router'


export default {
    setup() {
        const list = [
            {
                path: '/home',
                name: 'home',
                label: 'Home',
                icon: 'home',
                url: '/home'
            },
            {
                path: '/other',
                name: 'other',
                label: 'Other',
                icon: 'location',
                url: 'other'
            },
        ];
        const router = useRouter()  // This is how to use router in Vue3, which is a bit different from Vue2. Pay attention to this.
        const handleClick = (item) => {
            router.push({
                name: item.names
            });
        }
        return {
            list,
            handleClick,
        }
    }
}
</script>

<style lang="less" scoped>
.icons {
    width: 18px;
    height: 18px;
    margin - right: 4px;
}
.el - menu - vertical - demo {
    width: 100%;
    border - right: none;
    h3 {
        color: #fff;
        text - align: center;
        margin - top: 10px;
    }
}
</style>

We’ve bound the click event to the el - menu - item tag, which triggers the handleClick function and passes in the item parameter. The content of the handleClick function is very simple, just for route jumping. Just look at the code.

Up to this point, the page routes can jump normally. You can run the project and click the left - hand menu bar to try.

Dynamic Routing

This note only introduced the case of fixed routes, that is, no matter who visits, the pages that can be accessed are exactly the same. In this case, fixed routes can be used, that is, writing the routes in the src/router/index.js file. However, it’s also possible that different people can access different pages. For example, people with different permissions can access different pages, etc. In this case, dynamic routing is needed.

The so - called dynamic routing means obtaining from the backend through an API which APIs this user should access. Generally, when a user logs in, an API is requested from the backend to obtain routing data and then rendered into vue - router. This is a bit complicated and not easy to explain in words. If you want to know more, refer to my code and this video for learning: https://www.bilibili.com/video/BV1QU4y1E7qo?p=87&vd_source=55550879a421ab9d1e89e4ff47481a4d