声明式路由传参
一.query 传参(可搭配path,name使用)
<!-- 路由跳转并携带参数,to的字符串写法 -->
<router-link :to="`/home/Message/detail?id=${item.id}&title=${item.title}`">首页</router-link>
<!-- 路由跳转并携带参数,to的对象写法(推荐) -->
<router-link :to="{
path:'/home/Message/detail',
query:{
id:item.id,
title:item.title
}
}">首页</router-link>
二.params传参(需要搭配name使用,不能用path)
router中路由参数是需要占位的
{
path:'Message',
component:Message,
children:[
{
name:'guanyu',
path:'detail/:id/:title',//使用占位符声明接收params参数
component:detail
}
]
}
<!-- 使用params传参(indx中要占位) -->
<!-- <router-link :to="`/home/Message/detail/${item.id}/${item.title}`">{{item.title}}</router-link> -->
<!-- 路由跳转并携带参数,to的对象写法(推荐) -->
<!-- 使用params传参(indx中要占位)使用下列这种方法,就要注意搭配name使用,不然会报错 -->
<router-link :to="{
// path:'/home/Message/detail',
name:'guanyu',
params:{
id:item.id,
title:item.title
}
}">{{item.title}}</router-link>
三.接受参数
(1)在跳转到的组件中使用以下访问传递的参数
this.$route.query.id
this.$route.params
(2) 在路由中,props声明的参数,在跳转到组件中,都能通过props接收
{
path:'Message',
component:Message,
children:[
{
name:'guanyu',
path:'detail',//使用占位符声明接收params参数
component:detail,
// props的第一种写法,值为对象,该对象中所有key-value都会以props的形式传给detail组件
// props:{a:1,b:'hello'}
// props的第二种写法,值为布尔值,如果布尔值为真,就会把该路由组件收到的所有params参数,以props的形式传递一个detail组件
// props:true
// props的第三种写法,值为函数
props($route){
return {id:$route.query.id,title:$route.query.title}
}
}
]
}
编程式路由跳转及其传参
好处:就是可以给按钮绑定点击事件,进行路由跳转
this.$router.push() 向历史栈中添加一条记录
this.$router.replace() 替换历史栈中当前记录
pushShow(item){
// 获取路由器的实例对象VueRouter的原型上有push,replace的方法
// console.log(this.$router)
this.$router.push({
name:'guanyu',
query:{
id:item.id,
title:item.title
}
})
},
replaceShow(item){
this.$router.replace({
name:'guanyu',
query:{
id:item.id,
title:item.title
}
})
}