我目前正在使用vuejs和vuex。这是我的问题:
我有一个包含所有数据的商店
state: {
articles: [{
title: "Article 1",
id: 1,
tag: "Tutorial"
}, {
title: "Article 2",
id: 2,
description: "Article 2",
tag: "Review"
}
}]
}
在主页上,我想显示所有类型的文章。在教程页面上,我只想显示带有“教程”等标签的文章......
我正在使用vue-router
。我正在使用计算属性和v-for
,所以我可以循环文章。
computed: {
articles() {
if (this.$route.meta.title == 'Tutorial') {
return this.$store.state.articles.tag == 'Tutorial'
}
if (this.$route.meta.title == 'Review') {
return this.$store.state.articles.tag == 'Review'
}
else if (this.$route.meta.title == 'Home') {
return this.$store.state.articles
}
}
}
我知道return this.$store.state.articles.tag == 'Tutorial'
无法正常工作,我正在寻找一种正确编码的方法,但我被卡住了!
此外,如果你有一个完全不同的更好的方法,请随时告诉我!
感谢您的时间 :)
正如大家所提到的,你需要使用过滤器,但作为一种模式,当你从vuex状态访问属性时你应该用vuex getters
构造它不要直接访问它们但是正确的是使用getter
Moe x s。 X。
const store = new Vuex.Store({
state: {
articles: [
{
title: "Article 1",
id: 1,
tag: "Tutorial"
},
{
title: "Article 2",
id: 2,
description: "Article 2",
tag: "Review"
}
]
},
getters: {
allArticles: state => {
return state.articles
},
tutorialArticles: state=>{
return state.articles.filter(article=>articles.tag=='Tutorial')
},
reviewArticles: state=>{
return state.articles.filter(articles=>articles.tag=='Review')
}
}
})
//end of vuex store
然后在您使用的“所有文章”组件中
computed:{
articles(){
return this.$store.getters.allArticles;
}
}
然后在您使用的教程文章组件中
computed:{
articles(){
return this.$store.getters.tutorialArticles;
}
}
这非常重要,因为如果您需要更改过滤方法的代码,您可以在一个地方进行更改,这就是使用Vuex的目的
可能最好的方法是使用.filter()
var obj = {state: {
articles: [{
title: "Article 1",
id: 1,
tag: "Tutorial"
}, {
title: "Article 2",
id: 2,
description: "Article 2",
tag: "Review"
}
]}}
var filtered = obj.state.articles.filter(o=>o.tag == "Tutorial");
console.log(filtered)