javascript - 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"
.
有任何想法吗?谢谢!
解决方案
您可以使用 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>
推荐阅读
- python - 在没有逗号分隔的python列表中选择一个元素
- c# - 笛卡尔积应该存储在单个表中还是应该拆分
- cakephp - 在 CakePHP 3 中为表分配一个人类可读且可动态检索的标题或别名
- google-analytics - Google Analytics 不会跟踪来自 Google Ads 的会话
- python - 使用 xpath,scrapy 在“THIS”选择器内循环
- javascript - HTML如何更改图像onClick
- rxjs - Subject 类的 isStopped 和 closed 属性有什么区别?
- java - 为什么从 Java DES KeyGenerator 生成的密钥大小不正确?
- apache-spark - 如何为 Spark Structured Streaming 中的每个微批量写入记录生成时间戳?
- node.js - Node.js同时读取和写入流到同一个文件