【Vue】Vue-Router传参的三种方式
结合两位博主,按照自己容易理解方式做了归纳
一共三种:
- 动态路由传参
- this.$router.push params(通过name映射)
- this.$router.push query(通过path映射)
一、动态路由传参
(1)路由配置(冒号声明变量)
{path: '/father/son/:id', name: D, component: D}
(2)地址栏中的显示
http://localhost:8080/#/father/son/44
(3)传值(字符串拼接形式)
<router-link :to="'/user/'+userid" tag="button">用户</router-link>
or
<a @click="clickHand(123)">push传参</a>
methods: {
clickHand(id) {
this.$router.push({
path: `/d/${id}`
})
}
}
(4)取值
子组件通过 this.$route.params.num 接受参数
mounted () {
this.id = this.$route.params.id
}
二、this.$router.push params(通过name映射)
//路由配置文件中
{
path: '/detail',
name: 'Detail',
component: Detail
}
//跳转时页面
this.$router.push({
name: 'Detail',
params: {
name: '张三',
id: 1,
}
})
// 取值
this.$route.params
地址栏显示
http://localhost:8080/detail/1
三、this.$router.push query(通过path映射)
//路由配置文件中
{
path: '/detail',
name: 'Detail',
component: Detail
}
//跳转时页面
this.$router.push({
path: '/detail',
query: {
name: '张三',
id: 1,
}
})
//跳转后页面获取参数对象
this.$route.query
地址栏显示
http://localhost:8080/#/detail?name=%E8%BF%99%E6%98%AF%E5%B0%8F%E7%BE%8A%E5%90%8C%E5%AD%A6
浙公网安备 33010602011771号