• 前端笔记(10) Vue3 Router 监听路由参数变化


    前言

    Vue Router是开发Vue项目的必不可少的工具,也是极为重要的学习要点。
    本篇介绍下Vue Router的基础使用和如何监听路由参数变化。

    Vue Router入门

    1 安装Router

    安装Vue Router非常方便,只需执行一个命令,如果还不知道怎么搭建Vue项目框架,可以参考我之前的博客:前端笔记(8) Vue3+Vite 搭建项目 配置路径别名@

    //npm
    npm install vue-router@4
    //yarn
    yarn add vue-router@4
    
    • 1
    • 2
    • 3
    • 4

    2 创建测试页面

    • 在src/views目录下,创建几个vue单文件组件,用来后面的测试。

    About.vue文件:

    <template>
      <p>我是About页面p>
    template>
    
    <script setup lang="ts">
    script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    Home.vue文件:

    <template>
      <p>我是Home页面p>
    template>
    
    <script setup lang="ts">
    script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    3 添加路由标签

    在src目录下面的那个App.vue文件添加2个路由标签
    App.vue文件:

    <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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    页面显示效果如下:
    在这里插入图片描述

    4 配置Router文件

    • 在src目录下新建router目录,然后在router目录里创建index.ts文件
    • 这里指定根路径/也跳转到/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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    5 配置main.ts文件

    • 在main.ts中引入上面创建的路由器配置文件
    • 然后app.use(router)
      在这里插入图片描述

    6 验证页面跳转效果

    在这里插入图片描述

    获取路由参数

    很多时候,我们的页面是需要接收参数的,比如下面创建一个用户页面User.vue,它接收一个参数id

    1 创建用户页面

    User.vue文件:

    <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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    2 添加2个链接

    在App.vue文件里继续添加2个跳转链接

    <router-link to="/user/1" active-class="active"> 【user/1】 router-link>
    <router-link to="/user/2" active-class="active"> 【user/2】 router-link>
    
    • 1
    • 2

    3 路由器配置文件添加路由配置

    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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    4 查看页面演示效果

    在这里插入图片描述
    如上图显示,第二个userId并没有跟着变化,因为用户从 /user/1 导航到 /user/2 时,相同的组件实例将被重复使用。因为两个路由都渲染同个组件,比起销毁再创建,复用则显得更加高效。不过,这也意味着组件的生命周期钩子不会被调用。

    解决上面的问题主要有2种方法:

    • 用watch()监听路由route的变化
    • 用beforeRouteUpdate导航守卫

    方法1:用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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    方法2:用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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    在这里插入图片描述

  • 相关阅读:
    linux正则表达式
    微信小程序第二篇:七种主流通信方法详解
    【智能家居项目】裸机版本——字体子系统 | 显示子系统
    RPA流程调试:准确定位错误原因及位置
    C++ 不知树系列之认识二叉树(顺序、链表存储的实现)
    5款堪称变态的AI神器,焊死在电脑上永不删除!
    [附源码]Python计算机毕业设计java高校社团管理系统
    PTA 甲级 1057 Stack
    uniapp读取和写入文件
    对JVM G1的理解
  • 原文地址:https://blog.csdn.net/winterking3/article/details/126279257