一、<> 方式跳转
1. 携带query参数
<router-link to="/detail?id=001&title=消息001"> 消息001</router-link>
<router-link :to="{
name: 'detail',
path: '/detail',
query: {
id: '001',
title: '消息001'
}
}"
注:开发公司此种方式不需要动,to开发公司属性对象形式中name和path开发公司二选一即可 。
开发公司此时浏览器地址栏地址为:http://localhost:8080/detail?id=001&title=消息001
开发公司接收参数为:
$route.query.xxx
2. 携带params参数
<router-link :to="`/detail/${id}/${title}`"> {{ title }} </router-link>
<router-link :to="{
name: 'detail',
path: '/detail',params: {
id: '001',
title: '消息001'
}
}"
注意:开发公司此种方式需要修改路由配置,且to的对象形式中只能用name匹配路由
{
name: 'detail',
path: '/detail/:id/:title'
component: Detail
}
此时浏览器地址栏地址为:http://localhost:8080/detail/001/消息001
接收参数为:
$route.params.xxx
3.将参数转换为props属性
我们可以通过配置路由时的props属性,将params/query携带的参数,在组件中用props属性来接收,这样用时可以直接使用,就不需要$route.params.xxx/$route.query.xxx的形式了
配置方式:
- {
- name:'detail',
- path:'/detail',
- component: Detail,
-
- /**
- 方式一,值为对象,对象中的key-value会以props的形式传递给Detail组件,
- 但是传递的值都是一样的,不推荐
- props: {
- id: '123',
- title: '消息001',
- },
- **/
-
-
- /**
- 方式二,值为布尔值,若布尔值为真,就会把该组件收到的所有params参数,以props的形式传式传递给Detail组件, 但之这种方式只适用于params参数
- props: true,
- **/
-
- /**
- 方式三,值为函数,内置传参$route,可以使用结构赋值形式
- **/
- props({query}){
- return {id: query.id, title: query.title}
- },
还学到了一种结构再结构的形式
props({ query: { id, title } }) {
return { id, title }
二、编程方式跳转路由
通过编写代码的方式使路由发生跳转,跳转方式有两种,一种是push,一种是replace,他们都是$router上的函数(存在于原型上)。此时携带参数方式为:
- this.$router.push({
- name: 'detail',
- params: {
- id: xxx,
- title: xxx
- },
- /**
- query: {
- id: xxx,
- title: xxx
- }
- **/
- })
-
- this.$router.replace({
- name: 'detail',
- params: {
- id: xxx,
- title: xxx
- },
- /**
- query: {
- id: xxx,
- title: xxx
- }
- **/
- })
注意:不论何种方式跳转,想要在标签中接收到不同的params就需要在路由配置时用/:占位,不然只能接收到第一次打开时带过来的参数。
写在最后:
如果有建议或意见,欢迎评论。如果有小伙伴发现文中存在错误,也欢迎在评论区指出~