路由传参
- 首先,你需要在路由配置中定义路由参数。假设你有两个路由组件:
Home和Detail,你想要将Home组件中的某个数据传递给Detail组件。你可以在路由配置中定义一个路由参数来接收该数据。假设你想传递的数据是id,那么你可以这样配置路由:
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/detail/:id',
name: 'Detail',
component: Detail
}
]
- 在
Detail组件中,你可以通过$route.params来获取路由参数的值。在这个例子中,你可以通过$route.params.id来获取id的值。
- 接下来,在
Home组件中,你可以使用router-link来导航到Detail组件,并传递参数。示例如下:
<template>
<div>
<router-link :to="'/detail/' + itemId">Go to Detail</router-link>
</div>
</template>
<script>
export default {
data() {
return {
itemId: 1
}
}
}
</script>
- 在上面的示例中,我们使用了
:to绑定了动态的路由路径'/detail/' + itemId,其中itemId是Home组件的一个数据。
- 这样,当用户点击
Go to Detail链接时,将导航到Detail组件,并且路由参数id的值将是itemId的值
- 在
Detail组件中,你可以像下面这样获取路由参数的值:
<template>
<div>
<p>Detail Component</p>
<p>Id: {{ $route.params.id }}</p>
</div>
</template>
<script>
export default {
mounted() {
console.log(this.$route.params.id);
}
}
</script>
- 通过这种方式,你可以在路由之间传递参数并进行通信。
使用路由状态(Route State)
- 使用路由状态(Route State):你可以在路由导航时使用
router.push或router.replace方法的第二个参数来传递数据。这些数据将被存储在路由的状态中,可以在目标组件中访问。示例代码如下:
this.$router.push({ name: 'Detail', params: { id: 1 }, query: { name: 'example' } });
- 在Detail组件中,你可以通过
$route.params和$route.query来获取路由状态中的参数值:
<template>
<div>
<p>Detail Component</p>
<p>Id: {{ $route.params.id }}</p>
<p>Name: {{ $route.query.name }}</p>
</div>
</template>
this.$router 是 Vue Router 实例,通过它可以进行路由导航操作。
.push() 是 this.$router 的方法之一,用于将用户导航到新的路由。
{ name: 'Detail' } 是作为 push 方法的参数,用于指定目标路由的名称。在路由配置中定义了名为 'Detail' 的路由。
name: 'Detail' 是通过路由配置对象中的 name 属性来定义的。在 Vue Router 的路由配置中,每个路由对象都可以包含一个 name 属性,用于给路由命名。这个 name 属性是一个字符串,用于标识该路由的名称。
{
path: '/detail',
name: 'Detail',
component: DetailComponent
}