search
HomeWeb Front-endVue.jsVue3+TS+Vite development skills: How to use Vue Router for routing management

Vue3+TS+Vite development skills: How to use Vue Router for routing management

Sep 11, 2023 pm 12:31 PM
vue: The third major version of vuejsts: abbreviation for typescript

Vue3+TS+Vite开发技巧:如何使用Vue Router进行路由管理

Vue3 TS Vite development tips: How to use Vue Router for routing management

In recent years, the Vue framework has become more and more popular among developers in the field of front-end development. In the Vue ecosystem, Vue Router, as a modern routing management tool, can help us build single-page applications with a good user experience. This article will share the development skills of using Vue Router with Vue3 and TypeScript for routing management.

1. Install and initialize Vue Router

First, we need to install Vue Router using npm or yarn command. Open the terminal and execute the following command:

npm install vue-router@next

Then, in the entry file (main.ts or main.js) of the Vue3 project, we need to introduce the Vue Router and associate it with the Vue application. The sample code is as follows:

import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import App from './App.vue'
import Home from './views/Home.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  }
  // 其他路由配置
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

createApp(App)
  .use(router)
  .mount('#app')

In the above sample code, we first created a Vue Router instance through the createRouter function, and configured the routing history mode and routing table. Then, a Vue application instance is created through the createApp function, and the created Vue Router instance is registered into the Vue application through the use method.

2. Define routes and components

In the previous step, we have configured a basic routing table. In this example, we only added a route named Home and set its corresponding component to the Home component. Next, we need to create this component.

In the src/views directory, create a file named Home.vue, and edit the file content as follows:

<template>
  <div>
    <h1 id="首页">首页</h1>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  name: "Home"
})
</script>

<style scoped>
</style>

In this sample code, we use the new features of Vue— —Composition API. Define a component through the defineComponent function and export this component. In this component, we simply render a div element containing the "Home" title.

3. Navigation and route jump

Based on the first two steps, we have been able to successfully create a basic Vue Router application. Next, we will introduce some related methods and techniques for navigation and routing jumps provided by Vue Router.

  1. Use the component for navigation

Vue Router provides a convenient component to implement the routing navigation function. In the template, we only need to use and set the to attribute to specify the routing path that needs to be jumped.

The sample code is as follows:

<template>
  <div>
    <h1 id="首页">首页</h1>
    <router-link to="/about">关于我们</router-link>
  </div>
</template>

In this example, we added a component to the Home component. Clicking this component will jump to "/about "path.

  1. Use the router.push() method for programmatic navigation

In addition to using the component in the template for navigation, Vue Router also provides programmatic navigation navigation method. We can use the router.push() method in the component script to perform routing jumps.

The sample code is as follows:

import { defineComponent } from 'vue'
import { useRouter } from 'vue-router'

export default defineComponent({
  name: "Home",
  methods: {
    goToAbout() {
      const router = useRouter()
      router.push('/about')
    }
  }
})

In this example, we define a goToAbout method, use the useRouter function inside the method to obtain the current Vue Router instance, and pass router.push('/about ') to perform route jump.

4. Dynamic routing and routing parameters

Vue Router also supports dynamic routing and routing parameters. By configuring placeholders in the routing path, we can create a routing path containing dynamic parameters and obtain the values ​​of routing parameters through the $route.params object.

The sample code is as follows:

const routes = [
  {
    path: '/user/:id',
    name: 'User',
    component: User
  }
  // 其他路由配置
]

const User = defineComponent({
  name: "User",
  props: {
    id: {
      type: Number,
      required: true
    }
  },
  created() {
    console.log(this.id) // 输出路由参数id的值
  }
})

In the above example, we define a routing path /user/:id that contains dynamic parameters, and receive and verify the values ​​of routing parameters through the props attribute . In the created life cycle hook function of the User component, we can output the value of the routing parameter id through console.log(this.id).

5. Routing Guard

In actual projects, we often need to perform some additional logic processing before routing jumps, such as user login verification, page permission control, etc. Vue Router provides route guards to meet these needs.

The three commonly used routing guards of Vue Router are beforeEach, beforeEnter and beforeLeave. They are triggered respectively before the route jumps, before entering a certain route, and before leaving a certain route.

The sample code is as follows:

router.beforeEach((to, from, next) => {
  // 逻辑处理
  next()
})

router.beforeEnter((to, from, next) => {
  // 逻辑处理
  next()
})

router.beforeLeave((to, from, next) => {
  // 逻辑处理
  next()
})

In the above example, we register the global routing guard through the corresponding method of the router object, and perform additional logic processing in the callback function. After processing the logic, continue the routing jump by calling the next() method.

6. Summary

Vue Router is an important part of the Vue ecosystem, and its application in the Vue3 TS Vite development environment has become simpler and more flexible. This article shares some key tips on how to use Vue Router for route management, including installing and initializing Vue Router, defining routes and components, navigation and route jumps, dynamic routes and route parameters, and route guards.

By mastering these skills, we can better use Vue Router to build single-page applications with good user experience and play a greater role in front-end development. I hope this article can provide some help and guidance to readers in using Vue Router for routing management in the Vue3 TS Vite project.

The above is the detailed content of Vue3+TS+Vite development skills: How to use Vue Router for routing management. 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
Vue.js vs. React: Community, Ecosystem, and SupportVue.js vs. React: Community, Ecosystem, and SupportApr 27, 2025 am 12:24 AM

Vue.js and React each have their own advantages, and the choice should be based on project requirements and team technology stack. 1. Vue.js is community-friendly, providing rich learning resources, and the ecosystem includes official tools such as VueRouter, which are supported by the official team and the community. 2. The React community is biased towards enterprise applications, with a strong ecosystem, and supports provided by Facebook and its community, and has frequent updates.

React and Netflix: Exploring the RelationshipReact and Netflix: Exploring the RelationshipApr 26, 2025 am 12:11 AM

Netflix uses React to enhance user experience. 1) React's componentized features help Netflix split complex UI into manageable modules. 2) Virtual DOM optimizes UI updates and improves performance. 3) Combining Redux and GraphQL, Netflix efficiently manages application status and data flow.

Vue.js vs. Backend Frameworks: Clarifying the DistinctionVue.js vs. Backend Frameworks: Clarifying the DistinctionApr 25, 2025 am 12:05 AM

Vue.js is a front-end framework, and the back-end framework is used to handle server-side logic. 1) Vue.js focuses on building user interfaces and simplifies development through componentized and responsive data binding. 2) Back-end frameworks such as Express and Django handle HTTP requests, database operations and business logic, and run on the server.

Vue.js and the Frontend Stack: Understanding the ConnectionsVue.js and the Frontend Stack: Understanding the ConnectionsApr 24, 2025 am 12:19 AM

Vue.js is closely integrated with the front-end technology stack to improve development efficiency and user experience. 1) Construction tools: Integrate with Webpack and Rollup to achieve modular development. 2) State management: Integrate with Vuex to manage complex application status. 3) Routing: Integrate with VueRouter to realize single-page application routing. 4) CSS preprocessor: supports Sass and Less to improve style development efficiency.

Netflix: Exploring the Use of React (or Other Frameworks)Netflix: Exploring the Use of React (or Other Frameworks)Apr 23, 2025 am 12:02 AM

Netflix chose React to build its user interface because React's component design and virtual DOM mechanism can efficiently handle complex interfaces and frequent updates. 1) Component-based design allows Netflix to break down the interface into manageable widgets, improving development efficiency and code maintainability. 2) The virtual DOM mechanism ensures the smoothness and high performance of the Netflix user interface by minimizing DOM operations.

Vue.js and the Frontend: A Deep Dive into the FrameworkVue.js and the Frontend: A Deep Dive into the FrameworkApr 22, 2025 am 12:04 AM

Vue.js is loved by developers because it is easy to use and powerful. 1) Its responsive data binding system automatically updates the view. 2) The component system improves the reusability and maintainability of the code. 3) Computing properties and listeners enhance the readability and performance of the code. 4) Using VueDevtools and checking for console errors are common debugging techniques. 5) Performance optimization includes the use of key attributes, computed attributes and keep-alive components. 6) Best practices include clear component naming, the use of single-file components and the rational use of life cycle hooks.

The Power of Vue.js on the Frontend: Key Features and BenefitsThe Power of Vue.js on the Frontend: Key Features and BenefitsApr 21, 2025 am 12:07 AM

Vue.js is a progressive JavaScript framework suitable for building efficient and maintainable front-end applications. Its key features include: 1. Responsive data binding, 2. Component development, 3. Virtual DOM. Through these features, Vue.js simplifies the development process, improves application performance and maintainability, making it very popular in modern web development.

Is vue.js better than React?Is vue.js better than React?Apr 20, 2025 am 12:05 AM

Vue.js and React each have their own advantages and disadvantages, and the choice depends on project requirements and team conditions. 1) Vue.js is suitable for small projects and beginners because of its simplicity and easy to use; 2) React is suitable for large projects and complex UIs because of its rich ecosystem and component design.

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 Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

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.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

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