Home > Web Front-end > Vue.js > Vue3+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

PHPz
Release: 2023-09-11 12:31:41
Original
1319 people have browsed it

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
Copy after login

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')
Copy after login

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>首页</h1>
  </div>
</template>

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

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

<style scoped>
</style>
Copy after login

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>首页</h1>
    <router-link to="/about">关于我们</router-link>
  </div>
</template>
Copy after login

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')
    }
  }
})
Copy after login

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的值
  }
})
Copy after login

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()
})
Copy after login

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!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template