目录
- 路由传参接收以及传参对象为对象时的问题
- 场景
- 接收路由参数
- vue路由传参总结
- Vue路由传参
路由传参接收以及传参对象为对象时的问题
具体代码如下所示:
场景
<div @click='toDetail'>查看详情</div>
路由传参不能直接传一个对象,需要使用JSON.stringify()方法将其转换成一个字符串,然后在其他页面接受的时候再使用JSON.parse()方法转换成一个对象
const router = useRouter() | |
const toDetail = () => { | |
// 我使用的是Vue3,router要从useRouter获取 | |
router.push({ name: 'viewAttendPerson', params: { list: JSON.stringify(formObj.form.myMeetingParticipatorList) } }) | |
} |
接收路由参数
1. Vue3接收
import { useRoute } from "vue-router"; | |
setup() { | |
const route = useRoute() | |
const data = JSON.parse(route.params.list) | |
} |
2. Vue2接收
let data = this.$route.params.list | |
data = JSON.parse(data) |
vue路由传参总结
Vue路由传参
1.route-link路由导航
在to跳转链接后传递参数,获取时需要在路由配置path时注明,才能通过$route.params拿到
<router-link to="/a/123">routerlink传参</router-link> | |
// 跳转后拿到参数 | |
mounted () { | |
this.num = this.$route.params.num | |
} | |
//num是在配置路由路径时定义好的 | |
{path: '/a/:num', name: A, component: A} |
2.$router.push
push跳转时在函数内定义好携带过去的参数,在下个页面通过$route.params拿到
<button "deliverParams(123)">push传参</button> | =|
methods: { | |
deliverParams (id) { | |
this.$router.push({ | |
path: `/d/${id}` | |
}) | |
} | |
} | |
//拿到参数 | |
mounted () { | |
this.id = this.$route.params.id | |
} | |
//路由配置 | |
{path: '/d/:id', name: D, component: D} |
3.通过路由属性中的name匹配路由,再根据params传递参数
//写好要push去到的组件名 | |
<button @click="deliverByName()">params传参</button> | |
deliverByName () { | |
this.$router.push({ | |
name: 'B', | |
params: { | |
sometext: '一只羊出没' | |
} | |
}) | |
} | |
//跳转后params拿到数据 | |
<template> | |
<div id="b"> | |
This is page B! | |
<p>传入参数:{{this.$route.params.sometext}}</p> | |
</div> | |
</template> | |
//路由规则定义 | |
{path: '/b', name: 'B', component: B} |
4.通过query来传递参数
//定义路由事件 | |
<button "deliverQuery()">query传参</button> | =|
deliverQuery () { | |
this.$router.push({ | |
path: '/c', | |
query: { | |
sometext: '这是小羊同学' | |
} | |
}) | |
} | |
//跳转后拿到数据 | |
<template> | |
<div id="C"> | |
This is page C! | |
<p>这是父组件传入的数据: {{this.$route.query.sometext}}</p> | |
</div> | |
</template> | |
//路由配置 无需做任何额外配置 | |
{path: '/c', name: 'C', component: C} |
注:通过这种方式拿到的数据会显示在url中
http://localhost:8080/#/c?sometext=%E8%BF%99%E6%98%AF%E5%B0%8F%E7%BE%8A%E5%90%8C%E5%AD%A6
总结:
1.传参的是this.$router,接收参数是this.$route,易混淆。前者是VueRouter的实例对象,而后者则是一个跳转的路由对象,每一个路由都会有一个route对象,是一个局部的对象。
2.params是通过name属性传递数据给指定的组件,query是通过path的配置将数据传递到指定path的地址。
3.通过query传递的数据在刷新页面的时候不会消失,而params传递的数据刷新页面得时候会消失,可以通过本地存储解决。