search
HomeWeb Front-endVue.jsRouting function in Vue3: implementing routing jumps for SPA applications

Vue3 is one of the most popular JavaScript frameworks currently, and in recent updates, Vue3 has introduced some very useful new features, one of which is more powerful routing capabilities.

There are some differences between the routing function of Vue3 and Vue2, so we need to review the routing of Vue2 before learning the routing function of Vue3.

Routing in Vue2 is implemented by using Vue Router. First, we need to install Vue Router in the project and then configure it in the Vue instance. For a simple routing system, we only need to specify each path and its corresponding component:

import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/components/Home.vue'
import About from '@/components/About.vue'

Vue.use(Router)

export default new Router({
  routes: [
    { path: '/', component: Home },
    { path: '/about', component: About }
  ]
})

In the above code, we create a Vue Router instance that contains two routes: '/' and '/about'. When users visit these URLs, Vue Router will render the corresponding components.

The main change in routing in Vue3 is to simplify the use of routing functions by using a new API. Next, we will introduce the routing function in Vue3 in detail.

Create Vue3 routing

First, we need to install Vue Router 4:

npm install vue-router@4

Then, we need to import Vue Router in the Vue application and create a Vue Router instance:

import { createRouter, createWebHistory } from 'vue-router'
import Home from '@/components/Home.vue'
import About from '@/components/About.vue'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', component: Home },
    { path: '/about', component: About }
  ]
})

export default router

Note that unlike Vue2’s routing, we now use the createRouter() function to create routes instead of new Router().

The main change in routing in Vue3 is that the routing function adopts a more declarative approach. We use the createWebHistory() function to specify the use of HTML5 history mode. This is a relatively new technology that allows us to update the page URL more safely without reloading the entire page.

Define routing

The way to define routing is the same as Vue2. We can define routes using the routes array. Each route consists of a path and a corresponding component.

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

Route parameters

Using route parameters, we can make the URL have variable values. For example, we can configure the following route and URL:

const routes = [
  { path: '/user/:id', component: User }
]

This will make the :id part of the URL a parameter that can accept any string value, for example:

/user/1
/user/abc
/user/123abc

We can Use $route.params in the component to access routing parameters. For example:

export default {
  name: 'User',
  created() {
    console.log(this.$route.params.id)
  }
}

This will output the route parameters every time the component is created.

Named routing

We can name the route when defining it. This is useful for certain route navigation methods, for example:

const routes = [
  { path: '/', component: Home, name: 'home' },
  { path: '/about', component: About, name: 'about' },
  { path: '/user/:id', component: User, name: 'user' }
]

Define a named route, which we can access through the $name attribute.

router.push({ name: 'user', params: { id: 123 }})

This will jump to the User component with the parameter id.

Route Navigation

We can use the following methods to navigate to another route:

// 带路径的导航
router.push('/about')

// 带命名的导航
router.push({ name: 'user', params: { id: 123 }})

// 重定向到另一个路由
router.replace('/about')

When we use routing in a component, we can use the $route object to access the current route information.

export default {
  name: 'About',
  created() {
    console.log(this.$route.path)
  }
}

Route Guard

Route guard is a mechanism to inspect navigation, allowing us to execute code before or after intercepting all routes. In Vue3, we can use the following route guard:

const router = createRouter({
  routes: [...]
})

router.beforeEach((to, from, next) => {
  // 在此处添加路由守卫代码
  next()
})

In the beforeEach guard, we can check whether the user is logged in or make the user complete the necessary actions to continue the navigation.

Summary

Vue3 has some major improvements in routing, making it easier to use than Vue2. It takes a more declarative approach, making it easier to define and use routes. In addition, Vue3 also introduces HTML5 history mode, which makes routing more secure and usable.

Using Vue3's routing function can help you create your own SPA application, and you can easily jump and navigate.

The above is the detailed content of Routing function in Vue3: implementing routing jumps for SPA applications. 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
How Accurate Is It to Think of Vue.js's Virtual DOM as a Mirror of the Real DOM?How Accurate Is It to Think of Vue.js's Virtual DOM as a Mirror of the Real DOM?May 13, 2025 pm 04:05 PM

Vue.js' VirtualDOM is both a mirror of the real DOM, and not exactly. 1. Create and update: Vue.js creates a VirtualDOM tree based on component definitions, and updates VirtualDOM first when the state changes. 2. Differences and patching: Comparison of old and new VirtualDOMs through diff operations, and apply only the minimum changes to the real DOM. 3. Efficiency: VirtualDOM allows batch updates, reduces direct DOM operations, and optimizes the rendering process. VirtualDOM is a strategic tool for Vue.js to optimize UI updates.

Vue.js vs. React: Scalability and MaintainabilityVue.js vs. React: Scalability and MaintainabilityMay 10, 2025 am 12:24 AM

Vue.js and React each have their own advantages in scalability and maintainability. 1) Vue.js is easy to use and is suitable for small projects. The Composition API improves the maintainability of large projects. 2) React is suitable for large and complex projects, with Hooks and virtual DOM improving performance and maintainability, but the learning curve is steeper.

The Future of Vue.js and React: Trends and PredictionsThe Future of Vue.js and React: Trends and PredictionsMay 09, 2025 am 12:12 AM

The future trends and forecasts of Vue.js and React are: 1) Vue.js will be widely used in enterprise-level applications and have made breakthroughs in server-side rendering and static site generation; 2) React will innovate in server components and data acquisition, and further optimize the concurrency model.

Netflix's Frontend: A Deep Dive into Its Technology StackNetflix's Frontend: A Deep Dive into Its Technology StackMay 08, 2025 am 12:11 AM

Netflix's front-end technology stack is mainly based on React and Redux. 1.React is used to build high-performance single-page applications, and improves code reusability and maintenance through component development. 2. Redux is used for state management to ensure that state changes are predictable and traceable. 3. The toolchain includes Webpack, Babel, Jest and Enzyme to ensure code quality and performance. 4. Performance optimization is achieved through code segmentation, lazy loading and server-side rendering to improve user experience.

Vue.js and the Frontend: Building Interactive User InterfacesVue.js and the Frontend: Building Interactive User InterfacesMay 06, 2025 am 12:02 AM

Vue.js is a progressive framework suitable for building highly interactive user interfaces. Its core functions include responsive systems, component development and routing management. 1) The responsive system realizes data monitoring through Object.defineProperty or Proxy, and automatically updates the interface. 2) Component development allows the interface to be split into reusable modules. 3) VueRouter supports single-page applications to improve user experience.

What are the disadvantages of VueJs?What are the disadvantages of VueJs?May 05, 2025 am 12:06 AM

The main disadvantages of Vue.js include: 1. The ecosystem is relatively new, and third-party libraries and tools are not as rich as other frameworks; 2. The learning curve becomes steep in complex functions; 3. Community support and resources are not as extensive as React and Angular; 4. Performance problems may be encountered in large applications; 5. Version upgrades and compatibility challenges are greater.

Netflix: Unveiling Its Frontend FrameworksNetflix: Unveiling Its Frontend FrameworksMay 04, 2025 am 12:16 AM

Netflix uses React as its front-end framework. 1.React's component development and virtual DOM mechanism improve performance and development efficiency. 2. Use Webpack and Babel to optimize code construction and deployment. 3. Use code segmentation, server-side rendering and caching strategies for performance optimization.

Frontend Development with Vue.js: Advantages and TechniquesFrontend Development with Vue.js: Advantages and TechniquesMay 03, 2025 am 12:02 AM

Reasons for Vue.js' popularity include simplicity and easy learning, flexibility and high performance. 1) Its progressive framework design is suitable for beginners to learn step by step. 2) Component-based development improves code maintainability and team collaboration efficiency. 3) Responsive systems and virtual DOM improve rendering performance.

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

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools