在使用params传递参数时,需要使用name来指定目标,否则会出现数据传输失败
vue的路由传参共有三种方式
1.query传参:不管使用path还是name来匹配路由都可以,然后通过query来传递参数,这种情况下 query传递的参数会显示在url(浏览器上看到的链接)后面
//使用标签
<router-link :to='{path:"test_path",query:{id:1}}'>传1</router-link>
<router-link :to='{path:"/test_path",query:{id:2}}'>传2</router-link>
<router-link :to='{name:"test_path",query:{id:3}}'>传3</router-link>
//js
<button @click="btn1()">传1</button>
<button @click="btn2()">传2</button>
btn1(){
this.$router.push({path:'about',query:{id:1}})
},
btn2(){
this.$router.push({name:'about',query:{id:2}})
},
2.params传参:通过路由属性中的name来确定匹配的路由,通过params来传递参数。
<!-- 传递params参数时,是通过指定路由名称进行传递的 -->
<router-link :to='{ name: "test_path", params: { id: 3 } }'>传3</router-link>
//js
<button @click="btn2()">传2</button>
btn2(){
this.$router.push({name:'test_path',params:{id:2}})
},
3.路径传参:直接通过path,直接携带参数进行路由传参,使用该方式传值的时候,需要子路由提前配置好参数,接收时也是通过this.$route.params.id获取
配置如下:
{
path: '/test_path/:id',
name: 'test_path',
component: test_path
}
<router-link to='/test_path/1'>传1</router-link>
//js
<button @click="btn1()">传1</button>
btn1(){
this.$router.push({path:'/about/1'})
},