行业知识
Vue3全家桶 - VueRouter - 【4】路径参数
2026-11-19 04:58:57
来源:互联网转载
路径参数
- 在 VueRouter ��,可以在路径中使用一个动态字段来实现,我们称之为“路径参数”:
- 语法:
path: '/url/:params'
- 在展示的组件中访问路径参数:
- 选项式API:
- JS中采用 this.$route.params 来访问;
- 视图模板上采用 $route.params 来访问;
- 组合式API:
- 需要 import { useRoute } from 'vue-router';
- JS和视图模板上通过 useRoute().params 来访问;
- 还可以通过在路由规则上添加 props: true ,将路由参数传递给组件的 props 中;
- 示例展示:
- 基于上一小节的代码;
- 路由模块 - router/index.js:
import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'// TODO 创建路由规则数组const routes = [ { path: '/', // 路由重定向 redirect: '/guoMan' }, { path: '/teleplay', name: 'teleplay', component: () => import('@/views/Teleplay/index.vue'), children: [ { path: 'teleplayList/:id', // /:id - 路径参数 name: 'teleplayList', component: () => import('@/views/Teleplay/components/TeleplayList.vue'), props: true // 将路由路径上的动态参数,传递给组件的props } ] }, { path: '/guoMan', name: 'guoMan', component: () => import('@/views/GuoMan/index.vue'), children: [ { path: 'guoManList/:id', // /:id - 路径参数 name: 'guoManList', component: () => import('@/views/GuoMan/components/GuoManList.vue'), props: true // 将路由路径上的动态参数,传递给组件的props } ] }, { path: '/riMan', name: 'riMan', component: () => import('@/views/RiMan/index.vue'), children: [ { path: 'riManList/:id', // /:id - 路径参数 name: 'riManList', component: () => import('@/views/RiMan/components/RiManList.vue'), props: true // 将路由路径上的动态参数,传递给组件的props } ] }, { path: '/movie', name: 'movie', component: () => import('@/views/Movie/index.vue'), children: [ { path: 'movieList/:id', // /:id - 路径参数 name: 'movieList', component: () => import('@/views/Movie/components/MovieList.vue'), props: true // 将路由路径上的动态参数,传递给组件的props } ] }]// TODO 创建路由const router = createRouter({ // TODO 规定路由模式 // history: createWebHashHistory(), history: createWebHistory(), routes})export default router - 只展示一个目录中的,其他目录的都一样:
- views/GuoMan/index.vue:
import { ref, reactive, computed, onMounted } from 'vue'onMounted(() => {});国漫
展示国漫列表
h3 { color: #fff; font-size: 30px; font-family: '隶书';}.router-link { padding: 0 10px; color: #fff; font-size: 24px; font-family: '隶书';} - views/GuoMan/components/GuoManList.vue:
import { ref, reactive, computed, onMounted } from 'vue'import { useRoute } from 'vue-router'let list = ref([ { id: 'w45', title: '完美世界', }, { id: 'y43', title: '一念永恒' }, { id: 'z27', title: '赘婿' }])const props = defineProps({ id: { type: String }})// NOTE 获取的跳转的路由对象const routeObj = useRoute()onMounted(() => { console.log(routeObj.params)});- {{ title }}
路径参数 - id - useRoute().params读取 :{{ routeObj.params }}
路径参数 - id - useRoute().params.id读取 :{{ routeObj.params.id }}
路径参数 - id - props.id读取 :{{ props.id }}
li { list-style: none; padding: 0 10px; color: yellow; font-size: 24px; font-family: '隶书';}p { color: rgb(0, 255, 179); font-size: 24px; font-family: '隶书';} - 运行展示:
- views/GuoMan/index.vue:
- 选项式API:
- 语法:
上一篇:挂载服务器怎么理解?
下一篇:如何给系统加密?