Home Web Front-end Vue.js VUE3 Basic Tutorial: Routing and Navigation

VUE3 Basic Tutorial: Routing and Navigation

Jun 16, 2023 am 09:49 AM
vue navigation routing

VUE3 is one of the most popular front-end development frameworks currently, which provides a simple, flexible and efficient way to build modern web applications. Routing and navigation are one of the important functions in the VUE3 framework. Through them, you can easily switch and manage between pages.

This tutorial will introduce the basic concepts and usage of routing and navigation in the VUE3 framework, and help you quickly get started with the routing and navigation functions of VUE3.

  1. The basic concept of routing

Routing refers to the way to access different pages through different URLs. In VUE3, routing is implemented through the vue-router library. vue-router provides routing definition and management functions.

Before using vue-router, you need to install and introduce the vue-router library. The installation method is as follows:

npm install vue-router
Copy after login

The method of introducing the vue-router library is as follows:

import { createRouter, createWebHashHistory } from 'vue-router'
Copy after login

Among them, createRouter is the method used to create routes, and createWebHashHistory specifies the use of hash mode for routing.

When defining a route, you need to define the path and component of the route. Path is the URL to access the route, and component is the corresponding component.

For example:

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

The above code defines two routes, one is the root path '/', the corresponding component is Home; the other is '/about', the corresponding component is About .

When creating a routing instance, you need to pass in the defined routes, as shown below:

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

history specifies the routing mode, and createWebHashHistory indicates the use of hash mode. Other modes include history mode and abstract mode. routes refers to the routing configuration array.

  1. Basic concepts of navigation

In VUE3, after defining the URL and corresponding components through routing, you need to use navigation to switch and jump between pages. change.

Navigation mainly includes two methods: programmatic navigation and declarative navigation.

2.1 Programmatic Navigation

Programmatic navigation refers to page jumps and switches through JavaScript code. Vue Router provides some methods to implement this navigation method.

The following are some commonly used methods:

  • router.push: used to jump to the target page and add a new record to the routing history.
router.push('/home')
Copy after login
  • router.replace: used to jump to the target page, but does not add a new record to the routing history.
router.replace('/home')
Copy after login
  • router.go: Used to move forward or backward a specified number of steps in the routing history, which can be a positive or negative number.
router.go(-1) //后退一步
Copy after login

2.2 Declarative Navigation

Declarative navigation refers to switching and jumping pages through declarations in templates. In Vue Router, you can use the router-link component to implement declarative navigation.

The router-link component can be rendered as an a tag, used to jump to pages through routing links.

For example:

<router-link to="/home">Home</router-link>
Copy after login

The above code means rendering a link. Clicking the link will jump to the '/home' path.

At the same time, the router-link component also supports routing with parameters, for example:

<router-link :to="{ path: '/user/'+userId }">User</router-link>
Copy after login

The above code means rendering a link. Clicking the link will jump to the '/user/123' path. Among them, 123 is a user-defined parameter.

  1. Advanced concepts of routing

In VUE3, in addition to basic routing and navigation functions, there are also some advanced concepts of routing, such as routing nesting and naming. Routing, route guards, etc.

3.1 Route nesting

Route nesting refers to combining multiple routes together to form a parent-child relationship. In VUE3, route nesting is achieved by defining sub-routes.

For example:

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

In the above code, a parent route named Layout is defined, which contains two sub-routes, namely the root path '' and '/about'. The child route will be rendered in the parent route's .

3.2 Named routing

Named routing refers to defining a name for the route to facilitate calling it in the program. In Vue Router, the name of the route can be defined through the name attribute.

For example:

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

In the above code, the routes of the root paths '/' and '/about' are named home and about respectively.

In programmatic navigation and declarative navigation, page jumps and switches can be achieved through the corresponding route names.

3.3 Route guard

Route guard means that when the route jumps, the process of route jump can be controlled through some preset hook functions to achieve some specific requirements. In VUE3, Vue Router provides two types of global route guards and local route guards.

Global route guard refers to the unified control of all routes and is generally used for some global operations. The hook functions of the global routing guard include: beforeEach, beforeResolve and afterEach.

Local route guard refers to the specific control of a certain route or a group of routes, and is generally used for some local operations. The hook functions of local route guards include: beforeEnter, beforeRouteUpdate, and beforeRouteLeave.

For example:

router.beforeEach((to, from, next) => {
  // 进行权限判断或其他操作
  next()
})
Copy after login

In the above code, a global route guard is defined through the beforeEach function. to and from respectively represent the upcoming route and the current route, and next represents the function to release the route. It is required Call the next function in the guard to perform the route jump operation.

  1. Summary

This tutorial introduces the basic concepts and usage of routing and navigation in the VUE3 framework, as well as some advanced concepts. I hope that through this tutorial, you can master the basic usage of routing and navigation in VUE3, and be able to apply routing and navigation functions in actual projects.

The above is the detailed content of VUE3 Basic Tutorial: Routing and Navigation. 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
4 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
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
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.

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

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.

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