8、Vue 3 - Vue Router 使用实录 : 路由参数

作者: 温新

图书: 【Vue 3 Vue Router 使用实录】

阅读: 29

时间: 2024-05-18 08:18:14

为了保持文章的独立性,本篇文章还是把所有组件列表出来。

1、定义路由

src/router/index.ts

import { createRouter, createWebHistory } from "vue-router"

const router = createRouter({
    history: createWebHistory(),
    routes:[
		...
        {
            path:'/about',
            name:'about',
            component: () => import('@/views/AboutView.vue'),
            meta:{
                'title':'关于'
            },
            // 使用嵌套路由来演示路由参数
            // 1、开启路由参数
            children: [
                {
                    path:'/about/post/:id',
                    name:"Post",
                    component: () => import('@/views/PostView.vue'),
                    props:true	// 开启路由参数
                }
            ]
        },
		...
    ]
})

export default router
2、定义组件

src/views/PostView.vue

<template>
    <h1>文章:{{ id }}</h1>
</template>

<script setup lang="ts">
    import { watch } from 'vue';

    // 2、接收参数
    const props = defineProps({
        id:String
    })

    // 动态监听参数值的变化
    watch(() => props.id, () => {
        console.log(props.id);
    })

</script>
3、添加导航

src/views/AboutView.vue

<template>
    <div class="container bg-primary">关于</div>


    <div class="bg-success">
        <h6>我的文章</h6>
  
        <ul class="py-4 list-group">
            <li>
                <!-- 路由参数 -->
                <router-link to="/about/post/1" class="text-white">PHP</router-link>
            </li>
            <li>
                <router-link to="/about/post/2" class="text-white">Laravel</router-link>
            </li>
        </ul>
        <router-view></router-view>
    </div>
</template>
4、测试路由参数

浏览器中访问 http://localhost:5173/about 然后点价导航吧。

请登录后再评论