vue 项目路由传值的方式有哪些?
时间: 2023-03-05 07:38:21 浏览: 96
在 Vue 项目中,路由传值的方式有多种,以下是其中的几种常用方式:
1. URL 参数传递
通过 URL 的方式将参数传递给下一个路由。例如:
```javascript
// 在当前路由中,使用 router.push() 跳转到目标路由,并传递参数
this.$router.push({ path: '/destination', query: { id: 123 } })
// 在目标路由中,通过 $route.query 获取参数
this.$route.query.id // 输出 123
```
2. 动态路由传参
通过路由的动态匹配,将参数作为路由路径的一部分传递给下一个路由。例如:
```javascript
// 在路由中定义动态路径参数
const router = new VueRouter({
routes: [
{ path: '/destination/:id', component: Destination }
]
})
// 在当前路由中,使用 router.push() 跳转到目标路由,并传递参数
this.$router.push('/destination/123')
// 在目标路由中,通过 $route.params 获取参数
this.$route.params.id // 输出 123
```
3. 路由元信息传递
通过在路由配置中添加元信息的方式,将参数传递给下一个路由。例如:
```javascript
// 在路由中配置元信息
const router = new VueRouter({
routes: [
{
path: '/destination',
component: Destination,
meta: { id: 123 }
}
]
})
// 在目标路由中,通过 $route.meta 获取参数
this.$route.meta.id // 输出 123
```
需要注意的是,路由元信息传递的参数不会出现在 URL 中,因此不会被浏览器记录和收藏。此外,这种方式适合传递一些静态的参数信息,不适合传递动态的参数。