一、传参方式一:params
1、很多时候,我们需要将给定匹配模式的路由映射到同一个组件,例如:想渲染不同博客的内容,其实只是渲染到同一个组件上,只是博客的编号不同而已
2、在Vue Router中,可以在路径中使用一个动态字段来实现,我们称之为“路径参数” ,语法如:path: '/url/:param'
3、在展示的组件中访问路径参数
a. 在选项式 API中,采用this.$route.params来访问,视图模板上采用$route.params来访问
b. 在组合式 API 中,需要import { useRoute } from 'vue-router',JS和视图模板上通过useRoute().params来访问
c. 还可以通过在路由规则上添加props: true,将路由参数传递给组件的props中
实例:
src/router/index.js
import { createRouter,createWebHashHistory } from "vue-router";
import HomeView from '@/views/HomeView.vue'
import BlogHomeView from '@/views/blog/BlogHomeView.vue'
import BlogContentView from '@/views/blog/BlogContentView.vue'
let routes = [
{
path: '/',
redirect: '/home'
},
{
path: '/home', //URL地址
name: 'home', //名称
component: HomeView //渲染该组件
},
{
path: '/blog',
name: 'blog',
component:BlogHomeView,
children: [
{
path: 'blog-content/:id', //路径传参
name: 'blog-content',
component: BlogContentView,
props: true //将路径参数传递到展示组件的props中
}
]
}
]
//创建路由
const router = createRouter({
history: createWebHashHistory(), // 使用hash模式路由
routes //路由规则
})
export default router //暴露出去
App.vue
<script setup>
import { ref } from 'vue'
</script>
<!-- 视图区域(view) -->
<template>
<!-- 路由链接,点击后路由地址会切换到属性to的地方 -->
<router-link to="/home">首页</router-link>
<router-link to="/blog">博客</router-link>
<hr>
<!-- 路由视图,路由切换组件展示的地方 -->
<router-view/>
</template>
<style>
</style>
HomeView.vue
<template>
<div class="home">网站首页界面</div>
</template>
<style scoped>
div.home {
padding: 50px;
background-color: pink;
}
</style>
BlogHomeView.vue
<template>
<div class="blog">
博客首页界面:
<router-link to="/blog/blog-content/23">博客23</router-link>
<router-link to="/blog/blog-content/75">博客75</router-link>
<hr>
<router-view/>
</div>
</template>
<style scoped>
div.blog {
padding: 50px;
background-color: yellow;
}
</style>
BlogContentView.vue
<script setup>
import { useRoute } from 'vue-router';
const routeObj = useRoute() //获取跳转的路由对象
const propsData = defineProps(['id'])
function showRouteParams() {
console.log(routeObj.params) //获取路由路径参数对象
console.log(routeObj.params.id) //获取路由路径参数对象指定的属性
console.log(propsData.id) //在props取出路由路径参数
}
</script>
<template>
<div class="blog-content">
博客详情界面
<ul>
<li>{{ routeObj.params }}</li>
<li>{{ routeObj.params.id }}</li>
<li>{{ id }}</li>
</ul>
<button @click="showRouteParams">在JS中获取路由路径参数</button>
</div>
</template>
<style scoped>
div.blog-content {
padding: 50px;
background-color: rgb(228,78,190);
}
</style>
二、传参方式二:query
query参数会被添加到url的查询字符串中,它不需要再路由配置中指定任何特殊的行为,例如:
//路由跳转
router.push({path: '/register',query: {plan: 'private'}})
在组件中接收参数
export default {
mounted() {
console.log(this.$route.query.plan) //输出:private
}
}
注意:使用router.push或router.replace来进行路由跳转时,如果使用path,则需要手动拼接查询字符串;如果使用name,则可以方便地使用params和query对象。
Vue Router路径参数详解
6万+

被折叠的 条评论
为什么被折叠?



