Vue路由传参有以下6种方式:
- 路由路径参数(Route Params):在路由定义中使用动态路径参数来传递参数;适合传递单个参数,参数必须在路由定义中提前声明;使用场景:传递单个参数,例如用户ID、商品ID等。例如,定义一个带有参数的路由:
// 路由定义
{
path: '/user/:id',
name: 'user',
component: User
}
// 传递参数
this.$router.push({ name: 'user', params: { id: 123 } })
// 接收参数
this.$route.params.id
- 查询参数(Query Params):
在URL中使用查询字符串来传递参数。适合传递多个参数,参数较长时,URL可能会变得冗长;使用场景:传递多个参数,例如搜索条件、过滤条件。例如,定义一个带有查询参数的路由:
// 路由定义
{
path: '/user',
name: 'user',
component: User
}
// 传递参数
this.$router.push({ name: 'user', query: { id: 123 } })
// 接收参数
this.$route.query.id
- 路由元信息(Route Meta):
在路由定义中使用元信息来传递参数;适合传递静态参数,使用场景:传递静态参数,例如页面标题、页面权限。例如,定义一个带有元信息的路由:
// 路由定义
{
path: '/user',
name: 'user',
component: User,
meta: {
title: 'User Profile',
requiresAuth: true
}
}
// 获取参数
this.$route.meta.title
命名路由(Named Routes):
在路由定义中给每个路由设置一个唯一的名称,然后通过名称来传递参数。例如,定义一个带有命名路由的路由:
// 路由定义
{
path: '/user',
name: 'user',
component: User
}
// 传递参数
this.$router.push({ name: 'user', params: { id: 123 } })
// 接收参数
this.$route.params.id
在组件中可以通过router.push({ name: 'user', params: { id: 123 } })
- Props传递参数:
在路由定义中使用props属性来传递参数。例如,定义一个带有props的路由:
// 路由定义
{
path: '/user',
component: User,
props: true
}
// 接收参数
props: ['id']
在组件中可以通过props来接收参数:props: ['id']
Vuex状态管理:
使用Vuex来管理应用程序的状态,并在不同组件之间共享参数。通过在Vuex store中定义和更新参数,然后在组件中使用mapState或mapGetters来获取参数的值。
// Vuex store定义
const store = new Vuex.Store({
state: {
userId: null
},
mutations: {
setUserId(state, id) {
state.userId = id
}
}
})
// 设置参数
store.commit('setUserId', 123)
// 获取参数
this.$store.state.userId