search
HomeWeb Front-endVue.jsRouting control and management technology in Vue
Routing control and management technology in VueJun 25, 2023 am 08:31 AM
vuemanagement technologyrouting control

Vue is a very popular front-end framework. It provides a routing manager for convenient routing control and management. In this article, we will delve into the routing control and management technology in Vue to help developers better understand and apply these technologies.

1. Basics of Vue Router

Vue Router is the official routing manager of Vue.js. It is deeply integrated with the core of Vue.js and can well implement routing control of single-page applications. . Vue Router implements dynamic view updates by managing the mapping between routes and components, effectively isolating the view and data state, making the application structure clearer and easier to maintain.

1.1 Installation and introduction

Before using Vue Router, you need to install it through npm. You can install it through the following command:

npm install vue-router –save

After the installation is complete, you need to introduce Vue Router into the Vue application and perform basic configuration. You can write the following code in the main.js file:

import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'

Vue.use(VueRouter)

const routes = [{
  path: '/home',
  name: 'home',
  component: () => import('./pages/Home.vue')
}, {
  path: '/about',
  name: 'about',
  component: () => import('./pages/About.vue')
}, {
  path: '/contact',
  name: 'contact',
  component: () => import('./pages/Contact.vue')
}, {
  path: '*',
  redirect: '/home'
}]

const router = new VueRouter({
  mode: 'hash', // hash模式
  routes // 路由路径配置
})

new Vue({
  el: '#app',
  router, // 注册路由器
  render: h => h(App)
})

1.2 Routing Navigation

Vue Router provides multiple ways of routing navigation, including using the router-link tag to navigate and jump to pages. , wait for navigation to complete, etc.

Using the router-link tag in the component can easily implement route navigation, as shown below:

<router-link to="/home">首页</router-link>
<router-link to="/about">关于我们</router-link>
<router-link to="/contact">联系我们</router-link>

In addition, programmatic navigation can also be used to implement route jump, as shown below :

// 基本路由跳转
this.$router.push('/home')

// 带参数的路由跳转
this.$router.push({
  name: 'about',
  params: {
    id: 20,
    name: '张三'
  }
})

// 跳转后执行异步操作
this.$router.push('/about', () => {
  console.log('路由跳转完成')
})

// 返回前一个路由
this.$router.go(-1)

// 返回到命名路由
this.$router.push({
  name: 'home'
})

1.3 Routing Nesting

Vue Router supports the configuration of multi-level nested routing, which can achieve more complex routing control and management. For example, you can define sub-routes and nested sub-routes under the parent route, as shown below:

const routes = [{
  path: '/home',
  name: 'home',
  component: () => import('./pages/Home.vue')
}, {
  path: '/about',
  name: 'about',
  component: () => import('./pages/About.vue'),
  children: [{
    path: 'intro',
    name: 'about-intro',
    component: () => import('./pages/AboutIntro.vue')
  }, {
    path: 'contact',
    name: 'about-contact',
    component: () => import('./pages/AboutContact.vue')
  }]
}]

In the routing component, you can use the tag to occupy the sub-route. The parent route is a component, and the child route is rendered in the tag in this component, as shown below:

<template>
  <div>
    <h2 id="关于我们">关于我们</h2>
    <ul>
      <li><router-link :to="{ name: 'about-intro' }">公司简介</router-link></li>
      <li><router-link :to="{ name: 'about-contact' }">联系我们</router-link></li>
    </ul>
    <router-view></router-view>
  </div>
</template>

2. Vue Router Advanced

In addition to the basic In addition to routing management functions, Vue Router also provides some advanced functions, such as routing parameters, routing guards, dynamic routing, etc. In this section, we describe the usage and implementation of these features.

2.1 Routing parameter passing

In actual development, it is usually necessary to pass some parameters to the routing component, such as the information of the currently logged in user, article list, etc. In Vue Router, parameters can be passed through props attributes.

As shown below, when we define the route, we use the props attribute to transfer parameters:

const routes = [
  {
    path: '/user/:userId',
    name: 'User',
    component: User,
    props: true
  }
]

In the routing component, set props to true to use the routing parameters as the component's props attribute is passed. For example:

<template>
  <div>
    <h2 id="User-Details">User Details</h2>
    <p>{{ user.name }}</p>
    <p>{{ user.age }}</p>
  </div>
</template>

<script>
export default {
  props: ['user']
}
</script>

At this time, the routing parameters will be passed to the User component as the user attribute, and the component can obtain these parameters through this.user.

2.2 Route guard

Route guard is an important function provided by Vue Router, which can perform operations such as permission verification and login judgment during the route jump process. Vue Router provides three types of route guards: global guards, route-exclusive guards and intra-component guards.

Global guards include beforeEach, beforeResolve and afterEach, which are intercepted before the routing jump, after the jump is successful and after the entire routing process is completed. For example:

// 路由跳转前进行权限验证
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth) {
    if (authService.isAuthenticated()) {
      next()
    } else {
      next({
        name: 'login'
      })
    }
  } else {
    next()
  }
})

The route exclusive guard can be configured when the route is defined, or it can be configured inside the component. For example:

const router = new VueRouter({
  routes: [{
      path: '/admin',
      component: Admin,
      children: [
        {
          path: 'dashboard',
          component: Dashboard,
          beforeEnter: (to, from, next) => {
            if (authService.isAdmin()) {
              next()
            } else {
              next({
                name: 'login'
              })
            }
          }
        }]
      }]
 })

The guards within the component are the beforeRouteEnter, beforeRouteUpdate and beforeRouteLeave functions defined in the routing component. For example:

export default {
  beforeRouteEnter(to, from, next) {
    console.log('进入路由组件')
    next()
  },
  beforeRouteUpdate(to, from, next) {
    console.log('更新路由组件')
    next()
  },
  beforeRouteLeave(to, from, next) {
    console.log('离开路由组件')
    next()
  }
}

2.3 Dynamic routing

Dynamic routing refers to the technology of dynamically matching routes based on URL parameters. Vue Router provides dynamic matching capabilities based on routing parameters, and can perform routing jumps and component rendering based on different parameters.

For example, when defining a route, you can specify parameters by using a colon ":", as shown below:

const routes = [
  {
    path: '/posts/:postId',
    component: Post,
    props: true
  }
]

Inside the component, you can get the route through this.$route.params Parameters, as shown below:

export default {
  mounted() {
    console.log('PostComponent: ' + this.$route.params.postId)
  }
}

When routing jumps, you can use the $router.push method to perform dynamic route matching, for example:

this.$router.push({
  path: '/posts/' + id
})

3. Summary

This article introduces the basic use and advanced functions of Vue Router, including route navigation, route nesting, route parameter passing, route guards, and dynamic routing. Vue Router is an important routing manager in Vue.js, which can help us better implement routing control and management of front-end applications. I hope this article can inspire you and help you better apply Vue Router technology for development.

The above is the detailed content of Routing control and management technology in Vue. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Vue常见面试题汇总(附答案解析)Vue常见面试题汇总(附答案解析)Apr 08, 2021 pm 07:54 PM

本篇文章给大家分享一些Vue面试题(附答案解析)。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

5 款适合国内使用的 Vue 移动端 UI 组件库5 款适合国内使用的 Vue 移动端 UI 组件库May 05, 2022 pm 09:11 PM

本篇文章给大家分享5 款适合国内使用的 Vue 移动端 UI 组件库,希望对大家有所帮助!

vue中props可以传递函数吗vue中props可以传递函数吗Jun 16, 2022 am 10:39 AM

vue中props可以传递函数;vue中可以将字符串、数组、数字和对象作为props传递,props主要用于组件的传值,目的为了接收外面传过来的数据,语法为“export default {methods: {myFunction() {// ...}}};”。

手把手带你利用vue3.x绘制流程图手把手带你利用vue3.x绘制流程图Jun 08, 2022 am 11:57 AM

利用vue3.x怎么绘制流程图?下面本篇文章给大家分享基于 vue3.x 的流程图绘制方法,希望对大家有所帮助!

如何覆盖组件库样式?React和Vue项目的解决方法浅析如何覆盖组件库样式?React和Vue项目的解决方法浅析May 16, 2022 am 11:15 AM

如何覆盖组件库样式?下面本篇文章给大家介绍一下React和Vue项目中优雅地覆盖组件库样式的方法,希望对大家有所帮助!

聊聊vue指令中的修饰符,常用事件修饰符总结聊聊vue指令中的修饰符,常用事件修饰符总结May 09, 2022 am 11:07 AM

本篇文章带大家聊聊vue指令中的修饰符,对比一下vue中的指令修饰符和dom事件中的event对象,介绍一下常用的事件修饰符,希望对大家有所帮助!

通过9个Vue3 组件库,看看聊前端的流行趋势!通过9个Vue3 组件库,看看聊前端的流行趋势!May 07, 2022 am 11:31 AM

本篇文章给大家分享9个开源的 Vue3 组件库,通过它们聊聊发现的前端的流行趋势,希望对大家有所帮助!

react与vue的虚拟dom有什么区别react与vue的虚拟dom有什么区别Apr 22, 2022 am 11:11 AM

react与vue的虚拟dom没有区别;react和vue的虚拟dom都是用js对象来模拟真实DOM,用虚拟DOM的diff来最小化更新真实DOM,可以减小不必要的性能损耗,按颗粒度分为不同的类型比较同层级dom节点,进行增、删、移的操作。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools