Javascript 按标记Vuejs筛选数组

Javascript 按标记Vuejs筛选数组,javascript,vue.js,vuex,Javascript,Vue.js,Vuex,我目前正在使用vuejs和vuex。这是我的问题: 我有一个存储所有数据的商店 state: { articles: [{ title: "Article 1", id: 1, tag: "Tutorial" }, { title: "Article 2", id: 2, description: "Article 2", tag: "Review" } }] } 在主页上,我想显示所有种类的文章。在教程页面上,我只想显示带

我目前正在使用vuejs和vuex。这是我的问题:

我有一个存储所有数据的商店

state: {
  articles: [{
    title: "Article 1",
    id: 1,
    tag: "Tutorial"
  }, {
    title: "Article 2",
    id: 2,
    description: "Article 2",
    tag: "Review"
  }
 }]
}

在主页上,我想显示所有种类的文章。在教程页面上,我只想显示带有标签“tutorial”的文章,等等

我正在使用
vue路由器
。我正在处理一个计算属性和一个
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
            }
        }
    }
我知道
返回这个。$store.state.articles.tag=='Tutorial'
无法工作,我正在寻找正确编码的方法,但我被卡住了

另外,如果你有一个完全不同的更好的方法,请随时告诉我


谢谢您的时间:)

也许最好的方法是使用

var obj={状态:{
文章:[{
标题:“第1条”,
id:1,
标签:“教程”
}, {
标题:“第2条”,
id:2,
说明:“第2条”,
标签:“回顾”
}
]}}
var filtered=obj.state.articles.filter(o=>o.tag==“Tutorial”);

console.log(filtered)
正如大家提到的那样,您需要使用filter,但作为一种模式,您应该使用vuex getters来构建它 当您从vuex状态访问属性时,不要试图直接访问它们,但正确的做法是使用getter

Vuex商店e.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;
    }
 }
然后在教程文章中使用组件

 computed:{
    articles(){
      return this.$store.getters.allArticles;
    }
 }
 computed:{
    articles(){
       return this.$store.getters.tutorialArticles;
    }
 }

这是非常重要的,因为如果您需要更改筛选方法的代码,您可以在一个位置进行更改,这就是使用Vuex的目的,为什么不/不能使用一个简单的
筛选
数组方法?哦,我的天哪。我很笨。非常感谢。