我有一个组件,该组件需要一个食谱列表,并为数组中的每个项目创建一个组件。我正在尝试将配方对象传递给组件,然后使用Router-Link传递给第二个组件
<RecipeCard
v-for="recipe in filteredRecipes"
:key="recipe.id"
:recipe="recipe"
/>
在RecipeCard组件内部看起来像这样:
<template>
<div>
<router-link :to="{ path: 'recipe/' + recipe.id, props:{recipe} }">
<div>{{ recipe.title }}</div>
<p>
{{ recipe.description }}
</p>
</router-link>
</div>
</template>
我正在尝试将配方传递给另一个组件,因此,当单击配方卡时,它将打开一个详细视图。单击路由器链接后,它将定向到此页面:
<template>
<div>
<div>{{recipe.id}}</div>
</div>
</template>
<script>
export default {
name: 'PageViewRecipe',
props: {
recipe: {
type: Object,
required: true
}
},
data() {
return {
};
}
};
</script>
<style></style>
食谱是具有更多详细信息的对象。
import Vue from "vue";
import Router from "vue-router";
import Home from "./pages/PageHome";
import AddRecipe from "./pages/PageAddRecipe.vue";
import PageViewRecipe from "./pages/PageViewRecipe.vue"
Vue.use(Router);
const router = new Router({
mode: "history",
routes: [
{
path: "/",
name: 'Home',
component: Home,
},
{
path: "/add-recipe",
name: 'AddRecipe',
component: AddRecipe,
},
{
path: "/recipe/:id",
name: 'ViewRecipe',
component: PageViewRecipe,
props: true
}
],
});
export default router;
不幸的是,我的道具没有传递到最终组件。我尝试使用params,但似乎没有任何效果。
答案 0 :(得分:0)
vue-router
不会将道具从<router-link />
传递到在<router-view />
中渲染的组件。此外,<router-link />
doesn't support props
key in to
param。只是被忽略了。
相反,您可以做的是:
使用任何方法进行状态管理 as described in official documentation,因此PageViewRecipe
和RecipeCard
都可以访问相同的食谱列表。>
在PageViewRecipe
中,将id
传递给router-link。例如
<!-- BTW: you don't have to create path by yourself, let vue-router create it for you by combination of named router and params -->
<router-link :to="{ name: 'ViewRecipe', params: { id: recipe.id } }">
<div>{{ recipe.title }}</div>
<p>
{{ recipe.description }}
</p>
</router-link>
PageViewRecipe
内部,从共享位置(vuex,共享对象等)访问食谱列表,并找到具有ID的食谱,如下所示:<template>
<div>
<div>{{recipe.id}}</div>
<p>
{{ recipe.description }}
</p>
</div>
</template>
<script>
export default {
name: 'PageViewRecipe',
props: {
// passed by vue-router (from url), also available as this.$route.params.id
id: {
type: Number,
required: true
}
},
computed: {
recipe() {
// `this.recipes` comes from state management (for instance from vuex getter)
return this.recipes.find(recipe => recipe.id === this.id);
}
}
}
};
</script>
<style></style>
这种方法的好处是,您只发出一个API请求,并且由于您可以访问食谱的完整列表,因此您可以处理一些极端情况,例如不存在具有给定ID的食谱。 但是您可以尝试执行两个API调用,这样就不必处理共享状态管理。