search
HomeWeb Front-endVue.jsLet's talk about routing in Vue3 and briefly analyze routing configuration methods

This article will take you through routing in Vue3 and talk about the basic configuration of routing, dynamic routing configuration, routing mode, routing redirection, etc. I hope it will be helpful to you.

Let's talk about routing in Vue3 and briefly analyze routing configuration methods

[Related recommendations: "vue.js Tutorial"]

Basic configuration of routing

1. Install the plug-in

npm install vue-router@next --save

2, create a routers.ts file

3, introduce components in routers.ts and configure the path.

import { createRouter,createWebHashHistory } from 'vue-router';
// 引入组件
import Home from './components/Home.vue';
import News from './components/News.vue';
import User from './components/User.vue';

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {path: '/', component: Home},
    {path: '/news', component: News},
    {path: '/user', component: User},
  ]
})

export default router;

4. Mount the routing file to vue in main.ts.

import { createApp } from 'vue'
import App from './App.vue'
import routers from './routers';

// createApp(App).mount('#app')

const app = createApp(App);
app.use(routers);
app.mount('#app');

5. After the component that uses routing mounts router-link through the router-view component or router-link

<template>
  <img src="/static/imghwm/default1.png"  data-src="./assets/logo.png"  class="lazy"  alt="Vue logo" >
  <ul>
    <li>
      <router-link to="/">首页</router-link>
    </li>
    <li>
      <router-link to="/news">新闻</router-link>
    </li>
    <li>
      <router-link to="/user">用户</router-link>
    </li>
  </ul>

  <router-view></router-view>
</template>

, you only need to go to the page path corresponding to the component. Enter the specified route to complete the jump, and router-link implements routing in the form of a tag for jump.

Configuration of dynamic routing

Configure routing in routes.ts as follows, and configure dynamic routing through /:aid.

//配置路由
const router = createRouter({

    history: createWebHashHistory(),
    routes: [
        { path: &#39;/&#39;, component: Home , alias: &#39;/home&#39; },
        { path: &#39;/news&#39;, component: News },
        { path: &#39;/user&#39;, component: User },
        { path: &#39;/newscontent/:aid&#39;, component: NewsContent },
    ], 
})

When jumping through router-link, a template string and colon + to are required.

<ul>
    <li v-for="(item, index) in list" :key="index">
        <router-link  :to="`/newscontent/${index}`"> {{item}}</router-link>
    </li>
</ul>

Get the value passed by dynamic routing through this.$route.params.

mounted(){
    // this.$route.params 获取动态路由的传值
    console.log(this.$route.params)
}

If we want to achieve a value transfer similar to GET, we can use the following method

1. Configure the route as a normal route.

const router = createRouter({

    history: createWebHashHistory(),
    routes: [
        { path: &#39;/&#39;, component: Home , alias: &#39;/home&#39; },
        { path: &#39;/news&#39;, component: News },
        { path: &#39;/user&#39;, component: User },
        { path: &#39;/newscontent&#39;, component: NewsContent },
    ], 
})

2. Router-link jumps in the form of question marks.

<router-link  :to="`/newscontent?aid=${index}`"> {{item}}</router-link>

3. Get the get value through this.$route.query.

console.log(this.$route.query);

Routing programmatic navigation (JS jump routing)

Just need to specify it through this.$router.push.

  this.$router.push({
    path: &#39;/home&#39;
  })

If you want to implement get value transfer, you can use the following method.

this.$router.push({
    path: &#39;/home&#39;,
    query: {aid: 14}
  })
}

Dynamic routing needs to use the following method.

  this.$router.push({
    path: &#39;/home/123&#39;,
    // query: {aid: 14}
  })

Routing mode

Hash mode

The typical feature of Hash mode is that the page route contains a pound sign.

const router = createRouter({

    history: createWebHashHistory(),
    routes: [
        ...,
    ], 
})

HTML5 history mode

  • Introduces createWebHistory.

  • The history attribute in the router's configuration item is set to createWebHistory().

import { createRouter, createWebHistory } from &#39;vue-router&#39;

//配置路由
const router = createRouter({
    history: createWebHistory(),
    routes: [
        ...
    ], 
})

Note: After turning on HTML5 History mode, you need to configure pseudo-static when publishing to the server.

Configuring pseudo-static method:

https://router.vuejs.org/zh/guide/essentials/history-mode.html#Backend configuration example

Named routing

General situation

  • Configure the name attribute when defining the route

{ path: &#39;/news&#39;, component: News,name:"news" }
  • Pass in the object to jump

<router-link :to="{name: &#39;news&#39;}">新闻</router-link>

Pass the value through GET

  • When defining the route, configure the name attribute

{ path: &#39;/newscontent&#39;, component: NewsContent, name: "content" },
  • Pass in the object including query

<li v-for="(item, index) in list" :key="index">
    <router-link  :to="{name: &#39;content&#39;,query: {aid: index}}"> {{item}}</router-link>
</li>

Through dynamic Routing method

  • Define dynamic routing and specify the name attribute

{ path: &#39;/userinfo/:id&#39;, name: "userinfo", component: UserInfo }
  • Pass in the object including params

<router-link :to="{name: &#39;userinfo&#39;,params: {id: 123}}">跳转到用户详情</router-link>

Programmatic routing

is very similar to the above method.

<button @click="this.$router.push({name: &#39;userinfo&#39;,params: {id: 666}})">点击跳转</button>

Route redirection

{ path: &#39;&#39;, redirect: "/home" },   // 路由重定向
{ path: &#39;/home&#39;, component: Home },

Route alias

In the following example, accessing the people route is the same as accessing the alias route.

{ path: &#39;/user&#39;, component: User, alias: &#39;/people&#39; }

alias can also be an array.

{ path: &#39;/user&#39;, component: User, alias: [&#39;/people&#39;,&#39;/u&#39;]}

Form of dynamic routing.

{ path: &#39;/userinfo/:id&#39;, name: "userinfo", component: UserInfo, alias: &#39;/u/:id&#39; }

Nested routing

The application scenario of nested routing is generally on the navigation bar.

  • Define nested routing

{
  path: &#39;/user&#39;, component: User,
  children: [
    { path: &#39;&#39;, redirect: "/user/userlist" },
    { path: &#39;userlist&#39;, component: UserList },
    { path: &#39;useradd&#39;, component: UserAdd }
  ]
}
  • router-link and router-view display content together

<div class="left">
  <ul>
    <li>
      <router-link to="/user/userlist">用户列表</router-link>
    </li>
    <li>
      <router-link to="/user/useradd">增加用户</router-link>
    </li>
  </ul>
</div>
<div class="right">
  <router-view></router-view>
</div>

For more programming-related knowledge, please visit: Introduction to Programming! !

The above is the detailed content of Let's talk about routing in Vue3 and briefly analyze routing configuration methods. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
What Happens When the Vue.js Virtual DOM Detects a Change?What Happens When the Vue.js Virtual DOM Detects a Change?May 14, 2025 am 12:12 AM

WhentheVue.jsVirtualDOMdetectsachange,itupdatestheVirtualDOM,diffsit,andappliesminimalchangestotherealDOM.ThisprocessensureshighperformancebyavoidingunnecessaryDOMmanipulations.

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.

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 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

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.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.