query 传参
在我们 定义的 RouterLink to的路径后面加一个? 代表开始传参了
<RouterLink to="/news/detail?a=哈哈&b=你好&c=嘿嘿"></RouterLink>
第一种写法:
// 利用字符串拼接的方式进行传参
<RouterLink :to="/news/detail?id=${news.id}&title=${news.title}&content=${news.content}></RouterLink>
第二种写法:
<RouterLink
:to="{
path:'news/detail', // 配合路径使用
name:'detail', // 也可以配合name一起使用
利用对象的方式进行传参,这样比较方便一点
query:{
id:news.id,
title:news.title
content:news.content
}
}"></RouterLink>
接收路由传进来参数的时候
<script>
import {useRoute} from 'vue-router'
const route = useRoute() // Hooks 的用法
</script>
<template>
<ul>
<li>编号:{{route.query.id}}</li>
<li>编号:{{route.query.title}}</li>
<li>编号:{{route.query.content}}</li>
</ul>
</template>
params参数传参
<RouterLink :to="/news/detail/哈哈/嘿嘿/哎呦"></RouterLink>
//第一种写法, 纯字符串写法
<RouterLink :to="/news/detail/${news.id}/${news.title}/${news.content}"></RouterLink>
//第二种写法
<RouterLink
:to="{
name:'xiang',
params:{
id:news.id,
title:news.title,
content:news.content,
}
}"></RouterLink>
// 在 router 文件中 这样写
routes:[
{
name:'zhuye',
path:'/home',
components:Home
},
{
name:'xinwen',
path:'/news',
components:News,
children:[
{
name:'xiang'
path:'detail/:id/:title/:content?',
// ?可传可不传
component:Detail
}
]
}
]
// 要传进去的内容页面 代码
<script>
import {useRoute} from 'vue-router'
const route = useRoute()
</script>
<template>
<ul>
<li>编号:{{route.params.id}}</li>
<li>编号:{{route.params.title}}</li>
<li>编号:{{route.params.content}}</li>
</ul>
</template>
路由的props 配置
<template>
<ul>
<li>编号:{{id}}</li>
<li>编号:{{title}}</li>
<li>编号:{{content}}</li>
<li>编号:{{x}}</li>
<li>编号:{{y}}</li>
<li>编号:{{z}}</li>
</ul>
</template>
<script lang='ts' setup >
defineProps(['id','title','content'])
defineProps(['x',y,'z'])
</script>
// 路由中这样写
routes:[
{
name:'zhuye',
path:'/home',
components:Home
},
{
name:'xinwen',
path:'/news',
components:News,
children:[
{
name:'xiang'
path:'detail/:id/:title/:content?',
// ?可传可不传
component:Detail,
// 第一种写法,将路由收到的所有的params参数作为props传给路由参数
// props:true
// 第二种写法,函数写法,可以自己决定将什么作为props给路由组件
props(route){
return route.query //query 参数传参这样写
}
//对象写法,想要什么就传什么
props:{
x:100,
y:200,
z:300,
}
}
]
}
]