路由传参一般是通过query和params。传给路由组件的参数需要使用useroute获取当前路由对象,然后将对象中的query参数解构赋值然后在组件中就能使用了。比较麻烦。
<template>
<ul class="news-list">
<li>编号:{{ query.id }}</li>
<li>标题:{{ query.title }}</li>
<li>内容:{{ query.content }}</li>
</ul>
</template>
<script setup lang="ts" name="About">
import {toRefs} from 'vue'
import {useRoute} from 'vue-router'
let route = useRoute()
let {query} = toRefs(route)
//解构赋值,将route对象中属性名为query的值赋值给query
//从响应式对象中解构属性,这个属性就失去响应式了.
</script>
<style scoped>
.news-list {
list-style: none;
padding-left: 20px;
}
.news-list>li {
line-height: 30px;
}
</style>
props作用:让路由组件更方便的收到参数(可以将路由参数作为props
传给组件)
需要在下一级路由组件中的script里面用defineProps(['id','title','content'])接收
{
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组件(query参数不行)
// props:true
// props的函数写法,作用:把返回的对象中每一组key-value作为props传给Detail组件(参数是当前路由对象)
props(route){
return route.query
}
}