foreword
Vue Router is an indispensable tool for developing Vue projects, and it is also an extremely important learning point.
This article introduces the basic use of Vue Router and how to monitor changes in routing parameters.
Getting started with Vue Router
1 Install Router
It is very convenient to install Vue Router. You only need to execute one command. If you don’t know how to build a Vue project framework, you can refer to my previous blog: Front-end Notes (8) Vue3+Vite build project configuration path alias@
//npm
npm install vue-router@4
//yarn
yarn add vue-router@4
2 Create a test page
- In the src/views directory, create several vue single-file components for later testing.
About.vue file:
<template>
<p>我是About页面</p>
</template>
<script setup lang="ts">
</script>
Home.vue statement:
<template>
<p>我是Home页面</p>
</template>
<script setup lang="ts">
</script>
3 Add routing label
Add 2 routing tags to the App.vue file under the src directory
App.vue file:
<template>
<p>
<router-link to="/about" active-class="active"> 【about】 </router-link>
<router-link to="/home" active-class="active"> 【home】 </router-link>
</p>
<!-- 路由出口,路由匹配到的组件将渲染在这里 -->
<router-view />
</template>
<script setup lang="ts">
</script>
<style scoped>
.active {
color: red;
}
</style>
The page display effect is as follows:
<router-link>
Specifying the link via to will renderhref
a<a>
tag with the correct attribute<router-view />
It is the route exit, the components matched by the route will be rendered here
4 Configure Router file
- Create a new router directory under the src directory, and then create an index.ts file in the router directory
- Specify the root path here / also jump to /home
import {
createRouter, createWebHistory, RouteRecordRaw} from 'vue-router'
export const routes: Array<RouteRecordRaw> = [
{
path: '/',
redirect: '/home'
},
{
path: '/home',
component: () => import('@/views/Home.vue')
},
{
path: '/about',
component: () => import('@/views/About.vue')
}
]
const router = createRouter({
history: createWebHistory(),
routes: routes as RouteRecordRaw[]
})
export default router
5 Configure the main.ts file
- Introduce the router configuration file created above in main.ts
- Then app.use(router)
6 Verify page jump effect
Get route parameters
Many times, our pages need to receive parameters. For example, create a user page User.vue below, which receives a parameter id
1 Create user page
User.vue statement:
<template>
<p>
userId:{
{$route.params.id}}
userId:{
{userId}}
</p>
</template>
<script setup lang="ts">
import {
ref} from "vue";
import {
useRoute} from 'vue-router'
const route = useRoute()
let userId = ref<string | string[]>();
userId.value = route.params.id
</script>
2 Add 2 links
Continue to add 2 jump links in the App.vue file
<router-link to="/user/1" active-class="active"> 【user/1】 </router-link>
<router-link to="/user/2" active-class="active"> 【user/2】 </router-link>
3 Add routing configuration to the router configuration file
import {
createRouter, createWebHistory, RouteRecordRaw} from 'vue-router'
export const routes: Array<RouteRecordRaw> = [
{
path: '/',
redirect: '/home'
},
{
path: '/home',
component: () => import('@/views/Home.vue')
},
{
path: '/about',
component: () => import('@/views/About.vue')
}
,
{
path: '/user/:id',
component: () => import('@/views/User.vue')
}
]
const router = createRouter({
history: createWebHistory(),
routes: routes as RouteRecordRaw[]
})
export default router
4 Check the page demo effect
As shown in the figure above, the second userId does not change, because when the user navigates from /user/1 to /user/2, the same component instance will be reused. Because both routes render the same component, reuse is more efficient than destroying and recreating. However, this also means that the component's lifecycle hooks will not be called.
There are two main ways to solve the above problem:
- Use watch() to monitor changes in routing routes
- Navigation guards with beforeRouteUpdate
Method 1: Listening with watch()
<template>
<p>
userId:{
{$route.params.id}}
userId:{
{userId}}
</p>
</template>
<script setup lang="ts">
import {
ref, watch} from "vue";
import {
useRoute, onBeforeRouteUpdate} from 'vue-router'
const route = useRoute()
let userId = ref<string | string[]>();
userId.value = route.params.id
watch(
() => route.params,
(newValue, oldValue) => {
console.log(newValue)
console.log(oldValue)
userId.value = newValue.id
},
{
immediate: true }
)
</script>
Method 2: Navigation Guard with beforeRouteUpdate
<template>
<p>
userId:{
{$route.params.id}}
userId:{
{userId}}
</p>
</template>
<script setup lang="ts">
import {
ref, watch} from "vue";
import {
useRoute, onBeforeRouteUpdate} from 'vue-router'
const route = useRoute()
let userId = ref<string | string[]>();
userId.value = route.params.id
onBeforeRouteUpdate((to: any) => {
console.log(to.params.id);
userId.value = to.params.id
})
</script>