Home Web Front-end Vue.js Routing control and management technology in Vue

Routing control and management technology in Vue

Jun 25, 2023 am 08:31 AM
vue management technology routing 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
Copy after login

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)
})
Copy after login

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>
Copy after login

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'
})
Copy after login

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')
  }]
}]
Copy after login

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>关于我们</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>
Copy after login

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
  }
]
Copy after login

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>User Details</h2>
    <p>{{ user.name }}</p>
    <p>{{ user.age }}</p>
  </div>
</template>

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

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()
  }
})
Copy after login

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'
              })
            }
          }
        }]
      }]
 })
Copy after 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()
  }
}
Copy after login

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
  }
]
Copy after login

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)
  }
}
Copy after login

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

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

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 of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

React vs. Vue: Which Framework Does Netflix Use? React vs. Vue: Which Framework Does Netflix Use? Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

How to use vue traversal How to use vue traversal Apr 07, 2025 pm 11:48 PM

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values ​​for each element; and the .map method can convert array elements into new arrays.

See all articles