第二十:【路由的props配置】
作用:让路由组件更方便的收到参数(可以将路由参数作为props
传给组件)
{ name:'xiang', path:'detail/:id/:title/:content', component:Detail, 第一种方法: // props的对象写法,作用:把对象中的每一组key-value作为props传给Detail组件 // props:{a:1,b:2,c:3}, // props的布尔值写法,作用:把收到了每一组params参数,作为props传给Detail组件 // props:true 第二种方法: // props的函数写法,作用:把返回的对象中每一组key-value作为props传给Detail组件 props(route){ return route.query } }
路由规则的props 的写法:
第一种写法:在路由上:props:true 只支持 params 的形式
{
name:'xinwen',
path:'/news',
component:News,
children:[
{
name:'xiang',
path:'detail/:id/:title/:content?',
component:Detail,
// 第一种写法: // 第一种写法:将路由收到的所有params参数作为props传给路由组件
props:true,
}
]
},
第二步:在Detail.vue 页面中:
<template>
<ul class="news-list">
<li>编号:{{ id }}</li>
<li>标题:{{ title }}</li>
<li>内容:{{ content }}</li>
</ul>
</template>
<script setup lang="ts" name="About">
defineProps(['id','title','content']) // 执行这个defineProps 中包括的参数
</script>
第二种方法:支持query 模式:
// 第二种写法:函数写法,可以自己决定将什么作为props给路由组件
props(route){ // 引入 route 路由
return route.query
}
注意如果是 query 和 params 时的区别:
路由:query 模式下path 是这样的 path:'detail',
params 模式是这样写: path:'detail/:id/:title/:content?',
{
name:'xinwen',
path:'/news',
component:News,
children:[
{
name:'xiang',
path:'detail',
component:Detail,
// 第一种方法:
//props:true, // params模式下 path 要这样写:path:'detail/:id/:title/:content?',
// 第二种方法:
// 第二种写法:函数写法,可以自己决定将什么作为props给路由组件
props(route){ // query模式下 path 要这样写 path:'detail',
return route.query
}
}
]
},