Table of Contents
Step One: Installation
Step 2: Create a routing instance
Step 3: Mount the routing instance to the root instance
Step 4: Use routing-related components
Step 5: Use routing hook functions
Home Web Front-end Front-end Q&A An article introducing the steps to use Vue Router

An article introducing the steps to use Vue Router

Apr 26, 2023 pm 02:19 PM

With the continuous development of front-end technology, more and more applications are now beginning to adopt the single page application (Single Page Application, SPA) development method. As one of the important tools for front-end development, Vue.js has become one of the preferred frameworks for more and more developers. And when we use Vue.js to build a single-page application, Vue Router comes into being.

Vue Router is the official routing manager of Vue.js. It allows us to define application routing rules through simple configuration and map these rules to components to achieve page jump effects in single-page applications. In this article, we will introduce the steps to use Vue Router.

Step One: Installation

To use Vue Router, you first need to install it in the project. You can install it through npm or yarn:

npm install vue-router --save
Copy after login

or

yarn add vue-router
Copy after login

Step 2: Create a routing instance

The core part of Vue Router is to create a routing instance . We usually create this instance in the routing configuration file router.js (or other name). First, we need to introduce Vue and Vue Router:

import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
Copy after login

Then, we need to define routing rules:

const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About },
  { path: '/contact', component: Contact }
]
Copy after login

where routes is an array containing routing rules. Each routing rule is an object containing two attributes: path and component. Among them, path represents the path of the URL, and component is the component corresponding to the path.

Finally, we need to create a Vue Router instance and pass the routes rules we defined into it:

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

When creating the instance, we can configure some properties, such as mode and routes, etc. , these will be used to specify routing-related parameters.

Step 3: Mount the routing instance to the root instance

We will use the routing instance (Vue Router object) in the root instance, so we need to mount the instance to the root instance middle. For example:

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')
Copy after login

Here, we pass the routing instance (i.e. router) to our root Vue instance and render the root component (i.e. App) onto the #app node of the application.

When we have created a Vue Router instance and mounted it to the root Vue instance, we can then add it between Vue components Carry out route navigation.

In Vue Router, there are two important components: router-view and router-link. Router-view is used to display the specific content of routing components, while router-link is a link to navigate between different routes.

For example, in our application root component, we can use router-view to display the components corresponding to different routes:

<template>
  <div id="app">
    <nav>
      <router-link to="/">Home</router-link>
      <router-link to="/about">About</router-link>
      <router-link to="/contact">Contact</router-link>
    </nav>
    <router-view></router-view>
  </div>
</template>
Copy after login

Here, we have created some routes through the router-link tag Link. When the routing link is clicked, Vue Router automatically updates the URL and renders the routing component into router-view.

Step 5: Use routing hook functions

Vue Router also provides some hook functions (routing guards) to handle the logic in the navigation process. These routing hooks can be used globally or per route.

For example, in the global routing hook function beforeEach, we can implement the user's login verification logic:

router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth) {
    if (store.getters.isAuthenticated) {
      next()
    } else {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    }
  } else {
    next()
  }
})
Copy after login

In the above code, we use the beforeEach routing hook to check whether the user is authenticated. If the user has been authenticated, continue navigation; otherwise, redirect the user to the login page.

In addition to the beforeEach routing hook, Vue Router also provides some other hook functions used in the routing navigation process. For example, beforeRouteEnter is used to obtain the component instance object before entering a new route. beforeRouteUpdate is used to obtain the component instance object when the current component is reused. and beforeRouteLeave is used to obtain the instance object when the navigation leaves the current component.

The above are the steps for using Vue Router. Vue Router provides a very rich set of configuration options and routing hook functions, which can help us simplify the development process and improve application performance and user experience.

The above is the detailed content of An article introducing the steps to use Vue Router. 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 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)

How do you connect React components to the Redux store using connect()? How do you connect React components to the Redux store using connect()? Mar 21, 2025 pm 06:23 PM

Article discusses connecting React components to Redux store using connect(), explaining mapStateToProps, mapDispatchToProps, and performance impacts.

React's Role in HTML: Enhancing User Experience React's Role in HTML: Enhancing User Experience Apr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

How do you define routes using the <Route> component? How do you define routes using the <Route> component? Mar 21, 2025 am 11:47 AM

The article discusses defining routes in React Router using the &lt;Route&gt; component, covering props like path, component, render, children, exact, and nested routing.

What are the limitations of Vue 2's reactivity system with regard to array and object changes? What are the limitations of Vue 2's reactivity system with regard to array and object changes? Mar 25, 2025 pm 02:07 PM

Vue 2's reactivity system struggles with direct array index setting, length modification, and object property addition/deletion. Developers can use Vue's mutation methods and Vue.set() to ensure reactivity.

What are Redux reducers? How do they update the state? What are Redux reducers? How do they update the state? Mar 21, 2025 pm 06:21 PM

Redux reducers are pure functions that update the application's state based on actions, ensuring predictability and immutability.

What are Redux actions? How do you dispatch them? What are Redux actions? How do you dispatch them? Mar 21, 2025 pm 06:21 PM

The article discusses Redux actions, their structure, and dispatching methods, including asynchronous actions using Redux Thunk. It emphasizes best practices for managing action types to maintain scalable and maintainable applications.

What are the benefits of using TypeScript with React? What are the benefits of using TypeScript with React? Mar 27, 2025 pm 05:43 PM

TypeScript enhances React development by providing type safety, improving code quality, and offering better IDE support, thus reducing errors and improving maintainability.

How can you use useReducer for complex state management? How can you use useReducer for complex state management? Mar 26, 2025 pm 06:29 PM

The article explains using useReducer for complex state management in React, detailing its benefits over useState and how to integrate it with useEffect for side effects.

See all articles