【发布时间】:2023-03-06 04:27:01
【问题描述】:
我正在尝试使用 vuejs 制作博客,但我有点卡住了。 我所有的文章数据都在这样的 Vuex 商店中:
export const store = new Vuex.Store({
state: {
articles: [{
title: "Article 1",
id: 1,
content:"Article 1 content"
}, {
title: "Article 2",
id: 2,
content:"Article 2 content"
}
}]
}
我的主页上有一个文章网格:
<div class="item-article" v-for="article in articles">
<router-link :to="{path: '/article/'+article.id}"></router-link>
<div>{{ article.title }}</div>
</div>
当我点击一个网格文章时,我希望它重定向到 articlePage.vue 组件,其中包含相同 id 文章的数据。
到目前为止,在我的 articlePage.vue 组件中,我使用的是这个:
<div v-for="article in selectedArticle">
<h1>{{ article.title }}</h1>
<p>{{ article.content }}</p>
</div>
computed: {
selectedArticle(){
return this.$store.state.articles.filter(article => article.id == this.$route.params.id);
}
}
我想使用$route.params.id 来捕获 VueX 中匹配的 id,并访问正确的数据。但它不起作用。我做错了什么?
感谢您的帮助! :)
【问题讨论】:
-
您的路由器配置是什么样的?您是否看到任何错误消息,或者 ID 参数是否包含您期望的内容,或者文章数据没有显示,或者组件本身没有加载,还是什么? (“它不工作”很少有足够的信息继续下去;我们需要细节。)
-
是的,对不起,我的错应该更具体!我没有错误消息,当我 console.log(this.$store.state.articles) 我有包含所有数据的数组时,没关系!并且组件本身没有加载
-
即使它不是“最好”的 vue 方式(以下所有答案都是很好的答案,使用 vuex getter 和 props,使用
find而不是filter或使用name和 @987654329 @ 为您的router-link),您的代码实际上有效(fiddle here)。也许您只是忘记了router-view? -
哇,我很困惑,我很确定几个小时前它没有工作......我又试了一次,看起来还可以。巫术。
标签: javascript arrays vue.js vuex vue-router