我是 vue.js
的新手我正在尝试使用 vuex
.这是我的问题:
我有一个文章列表(它是一个组件)与商店链接 v-for="article in articles
和一个计算属性:
computed: {
articles() {
return this.$store.state.articles
}
}
这是我商店中的数据:
state: {
articles: [{
title: "Article 1",
id: 1,
description: "Article 1",
}, {
title: "Article 2",
id: 2,
description: "Article 2",
}
}]
}
当我点击一篇文章时,我希望它使用 <router-link :to="{path: '/article/'+article.id}"></router-link>
重定向到文章页面模板(它是一个组件) .
我想做的是将正确文章的数据绑定(bind)到 articlePage
中模板。
问题是,如果我将相同的计算属性应用于我的 articlePage.vue
带有 v-for
的组件, 我将在同一页面上显示所有文章。我只想显示匹配的 id 组件。
我该怎么做?
感谢您的宝贵时间:)
最佳答案
根据您的评论,我了解到您使用了 vue-router 模块
所以在你的 routes.js
(或 structure )你必须有这样的东西
const router = new VueRouter({
routes: [
{ path: '/articles', component: articlesPage },
{ path: '/article/:id', component: articlePage }
]
})
然后在您的文章页面组件中,您可以像这样提取“:id”:
this.$route.params.id
因为 vue-router 允许您使用方法和属性访问对象 $route
在这里查看更多 https://router.vuejs.org/guide/essentials/dynamic-matching.html
然后你可以用它来搜索文章数组并找到数据并呈现它们 例如
computed:{
selectedArticle(){
var article_id = this.$route.params.id;
var articles = this.$store.state.articles;
var article = null;
for(var a=0;a<articles.length;a++){
if(articles[a].id == article_id ){
article = articles[a];
break;
}
}
return article;
}
}
关于javascript - 使用 Vuex 将数据绑定(bind)到组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52150408/