首页 > 解决方案 > vuejs 按年份排序并在数组中按标签查找

问题描述

使用来自 api 的数据(使用 axios)在 VueJS 中构建项目:我有一个项目列表,其中包含道具(年份、位置等)和标签(房屋、公园等)。我制作了这个过滤器来切换按道具排序:

sortby(data) {
 // data = {prop: "year", tag: "house"}
 //
 if (data.prop === "year") {
   this.projects.sort((a, b) => (a[data.prop] < b[data.prop] ? 1 : -1));
 } else {
   this.projects.sort((a, b) => (a[data.prop] < b[data.prop] ? -1 : 1));
 }
},

但在排序之后,我只想显示具有tag === "house".

有任何想法吗?谢谢!

标签: javascriptarrayssortingvue.js

解决方案


您可以使用 javascript 数组过滤器

const filteredProjects = projects.filter(({tag}) => tag === "house");

或将其放在计算属性上

data: () => ({
  projects: [
    {prop: "year", tag: "house"},
    ...
  ]
}),
computed: {
    filteredProjects: function () {
      return this.projects.filter(({tag}) => tag === "house");
    }
  }

然后在您的模板中使用它

<template>
  <div>
    {{ filteredProjects }}
  </div>
</template>

推荐阅读