区分route和router两个对象:
$route对象:
$route对象表示当前的路由信息,包含了当前 URL 解析得到的信息。包含当前的路径,参数,query对象等。
$router对象:
$router对象是全局路由的实例,是router构造方法的实例。
场景: 点击父组件的li元素跳转到子组件中,并携带参数,便于子组件获取数据。
父组件:
<li v-for="article in articles" @click="getDescribe(article.id)">
1.直接调用$router.push实现携带参数跳转
getDescribe(id){
this.$router.push({
path:`/describe/${id}`
})
}
对应路由配置:
{
path:'/describe/:id',
name:'Describe',
component:Describe
}
需要在path中添加/:id来对应$router.push.path中path携带的参数。在子组件中可以使用来获取传递的参数值:
this.$route.params.id
2.父组件中通过路由属性中的name来确定匹配的路由,通过params来传递参数:
this.$router.push({
name:"Describe",
params:{
id:id
}
})
对应路由配置(不能使用:/id来传递参数):
{
path:'/describe',
name:'Describe',
component:Describe
}
子组件获取参数:
this.$route.params.id
3.this.$router.push({
path:'/describe',
query:{
id:id}
})
对应路由配置:
{ path: '/describe', name: 'Describe', component: Describe }
对应子组件: 这样来获取参数
this.$route.query.id
3.字符串
router.push('home')
4.对象
router.push({ path: 'home' })
5.命名的路由
router.push({ name: 'user', params: { userId: '123' }})
6.带查询参数,变成 /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})