vue router进行路由跳转并携带参数(params/query)
warning:
这篇文章距离上次修改已过190天,其中的内容可能已经有所变动。
在Vue Router中,可以使用$router.push
方法进行路由跳转,并且可以通过params
和query
来传递参数。
- 使用
params
传递参数时,需要在路由配置中指定props: true
,这样才能在目标组件中通过this.$route.params
获取到参数。
// 路由配置
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User, props: true }
]
})
// 跳转并携带参数
this.$router.push({ name: 'user', params: { id: 123 }})
// 在User组件中接收参数
export default {
props: ['id'],
created() {
console.log('User ID:', this.id)
}
}
- 使用
query
传递参数则不需要在路由配置中做特殊处理,参数会以查询字符串的形式附加到URL后面。
// 跳转并携带参数
this.$router.push({ path: '/search', query: { q: 'keyword' }})
// 在目标组件中接收参数
export default {
created() {
console.log('Search keyword:', this.$route.query.q)
}
}
以上代码展示了如何使用Vue Router进行路由跳转并携带参数。params
适合需要在URL中编码的场景,而query
适合非必要、可见的参数传递。
评论已关闭