1、router-link方式
1.1、不带参数跳转
<router-link :to="{name:'home'}">
<router-link :to="{path:'/home'}"> //name,path都行, 建议用name
注意:router-link中链接如果是'/'开始就是从根路由开始,如果开始不带'/',则从当前路由开始。
1.2、携带参数跳转
(1)params传参
<router-link :to="{name:'home', params: {id:1}}">
路由配置,若不配置path ,第一次可请求,刷新页面id会消失;配置path,刷新页面id会保留
path: "/home/:id"
path: "/home:id"
取参
$route.params.id //html 取参
this.$route.params.id //script 取参
(2)query
<router-link :to="{name:'home', query: {id:1}}">
路由可不配置
取参
$route.query.id // html 取参
this.$route.query.id // script 取参
2、编程式路由
2.1、不带参数
this.$router.push('/home')
this.$router.push({name:'home'})
this.$router.push({path:'/home'})
2.2、携带参数跳转
(1)query
this.$router.push({name:'home',query: {id:'1'}})
this.$router.push({path:'/home',query: {id:'1'}})
取参
this.$route.query.id
(2)params
this.$router.push({name:'home',params: {id:'1'}}) // 只能用 name
取参
this.$router.params.id
3、指定params参数可传可不传
(1)在占位后面加个问号,就不会出现路径有问题
path:'/search/:keyword?'
(2)如果传递的是空字符串,可以用undefined解决
this.$router.push({name:"login", params:{keyword:this.keyword||undefined}})
4、路由组件传递props数据
(1)布尔值写法:在路由配置项里写props:true(只能传递params参数)
{
path:'/search/:keyword?',
props:true
}
// 接收
props:['keyword']
// 使用
{{keyword}}
(2)对象写法:能携带一些额外参数
{
path:'/search/:keyword?',
props:{a:1,b:2}
}
// 接收
props:['keyword','a','b']
// 使用
{{a}}
(3)函数写法:params,query参数都能传递
{
path:'/search/:keyword?',
props($route)=>({keyword:$route.params.keyword})
}
// 接收
props:['keyword']
// 使用
{{keyword}}