The second chapter vue3 builds a view admin background management system——Vue Router detailed explanation

Series Article Directory

Chapter 1 vue3 builds view admin background management system - technology selection
Chapter 2 vue3 builds view admin background management system - Vue Router detailed explanation



foreword

In the previous article, we have completed the Vue3 project selection, and the routing management tool uses the officially recommended Vue Router. It is the first time to build a complete routing management. I recommend using the template provided by the iview recommended project. Although the template project has deleted some optimized designs, it is enough to build a simple routing management.


1. Example explanation of the official website

Let's take the sample code from the official website:

// 1. 定义路由组件.
// 也可以从其他文件导入
const Home = {
    
     template: '<div>Home</div>' }
const About = {
    
     template: '<div>About</div>' }

// 2. 定义一些路由
// 每个路由都需要映射到一个组件。
// 我们后面再讨论嵌套路由。
const routes = [
  {
    
     path: '/', component: Home },
  {
    
     path: '/about', component: About },
]

// 3. 创建路由实例并传递 `routes` 配置
// 你可以在这里输入更多的配置,但我们在这里
// 暂时保持简单
const router = VueRouter.createRouter({
    
    
  // 4. 内部提供了 history 模式的实现。为了简单起见,我们在这里使用 hash 模式。
  history: VueRouter.createWebHashHistory(),
  routes, // `routes: routes` 的缩写
})

// 5. 创建并挂载根实例
const app = Vue.createApp({
    
    })
//确保 _use_ 路由实例使
//整个应用支持路由。
app.use(router)

app.mount('#app')

The first step: define routing components, which are the pages that need to be navigated to one by one in our project.
Step 2: Define routing routes, which is an array of routing descriptions. Here, some attributes of each routing are defined. There are not many in total. You can browse the official website for details. You don’t need to remember, just have an impression.
Step 3: Call the createRouter method to get the router object.
Step 4: app.use(router) uses the plug-in.

2. Steps used in the project

The steps of the official example are designed to help us fully understand the steps of using vue router. In real projects, it must not be so simple to implement in a page or a module.
So we need to build a reasonable router routing management module for our real project.

1. Introduced as a plugin

If you have studied the previous article in this series, you should have a general understanding of the Vue file structure. All our plug-ins are introduced in main.js. Why are they only introduced in this entry file? For the answer, please read the previous article article.
Here only the usage is explained:

//引入
import router from '@/router/index.js'

//使用,router是其中一个插件,具体有多少个use,视项目引入多少插件而定
createApp(App).use(router).use(createPinia()).use(ViewUIPlus).mount('#app')

2.router module - index.js

From the path introduced above, we can see that we exposed all routing information in router/index.js, and then introduced and used it in main.js.
My router/index.js code is as follows:

import {
    
    createRouter,createWebHashHistory} from 'vue-router'
import {
    
    routes} from './router'
import {
    
      getToken } from '@/lib/util'

const router=createRouter({
    
    
    // history:createWebHistory(),
    history:createWebHashHistory(), //只能用hash模式
    routes
})

router.beforeEach((to,from)=>{
    
    
    const token = getToken()  //如果不涉及token,这句代码可删除
    if (
        // 检查用户是否已登录
        !token &&
        // ❗️ 避免无限重定向
        to.name !== 'login'
    ) {
    
    
        // 将用户重定向到登录页面
        return {
    
     name: 'login' }
    }
})

export default router

Because my project is a personal project, the routing management is actually relatively simple, and the token acquisition is only based on habit, which is added here. In fact, this project does not currently involve token verification.

The comment here says that only the hash mode can be used because of electron. If it is a simple vue3 front-end project, I personally recommend using the history mode.

This is our simplest routing management entry file. The only thing that needs to be improved by ourselves is the router.beforeEach part (navigation guard). This part needs to gradually add more business codes according to project requirements, and the rest are basically fixed.

Before all page routes are accessed, they will first go through the router.beforeEach part, so we can freely define in which conditions a certain route can be accessed, and under which conditions certain routes cannot be accessed, which is called navigation guard.

The second line of code here, the ./router file is the file where we define routing information. This is a modular idea. The code used by the routing plug-in is placed in main.js, the code of the routing operation is placed in router/index.js, and the code of the routing definition is placed in router/router.js.

3. router module - router.js

All routing information is defined in router.js.
The simplest example is just like the official website example, only the path and components, as follows:

const Home = {
    
     template: '<div>Home</div>' }
const About = {
    
     template: '<div>About</div>' }

const routes = [
  {
    
     path: '/', component: Home },
  {
    
     path: '/about', component: About },
]

Adapt to our file structure and transform it:

import Home from '@/views/Home.vue'
import About from '@/views/About.vue' //这两个组件的路径是我虚拟的,我们一般习惯在router.js文件中引入组件,而不是直接定义组件内容

export const routes = [
  {
    
     path: '/', component: Home },
  {
    
     path: '/about', component: About },
]

From this point of view, isn’t it much more comfortable? Let’s review the usage steps again:

  1. Introduce and use the router plugin in main.js
  2. Define the routing operation in the index.js file of the router module, import the routing information, and expose the routing object.
  3. Define routing information in the router.js file of the router module.

Summarize

This article briefly explains the steps to use the vue router tool, but this is far from enough to support the construction of an enterprise-level platform. A routing design that can be truly applied to actual combat projects must at least include icons, routing nesting, and other designs. How to build an enterprise-level navigation bar will be explained in the next article.

Guess you like

Origin blog.csdn.net/zjsj_lize/article/details/128375637