如何在vjs中优化此过滤方法?



我想优化一个方法,我用它来决定在故事中显示哪些值。我有一个表,显示不同的值,在它的顶部,有一些输入字段。输入字段中选择的值用于过滤表的内容。

<!-- the input fields-->
<v-select placeholder="Index" :options="indexList" v-model="filterTable['indexedValue']" @input="filteringTable"></v-select>
<v-select placeholder="Domain" :options="domainList" index="index" label="txt" v-model="filterTable['domainValue']" @input="filteringTable"></v-select>
<!-- table -->
<table>
<tbody>
<tr v-for="(value, i) in filteringTable()" :key="value.id">
...<!-- values shown here-->
</table>

在输入字段中选择的值被限定到对象filterTable。

data () {
return {
filterTable: {}
}
}

在输入时调用的方法定义如下:

filterTable () {
var newLinks = this.links // object containing all the info we want to show in the table
if (this.filterTable['indexedValue'] != null && this.filterTable['indexedValue'] !== undefined) {
newLinks = newLinks.filter(l => l.post.indexed === this.filterTable['indexedValue'])
}
if (this.filterTable['domainValue']) {
newLinks = newLinks.filter(l => l.tag.domain === this.filterTable['domainValue'])
}
return newLinks
}

(我的代码有2个以上的if语句,检查由其他输入字段给出的值,但它们也遵循上面相同的逻辑)
这段代码工作,它过滤表,但正如你所看到的,有两个许多if语句在它,我想知道是否有一些方法我可以遵循,使它更有效/优化?任何建议都是非常感谢的!

这里最好使用computed而不是方法。我还重命名了你的函数,因为名字可能有问题,因为它们是相同的:

computed: {
filter_table() {
return this.filterTable["domainValue"]
? this.links.filter(l => l.tag.domain === this.filterTable["domainValue"])
: this.links.filter(
l => l.post.indexed === this.filterTable["indexedValue"]
);
}
};
<tr v-for="(value, i) in filter_table" :key="value.id">

这个应该可以。

你也不需要像var newLinks = this.links这样的东西,你可以直接用this.links.filter()。Filter返回一个包含过滤值的新数组。

编辑:

你说如果两个条件都满足,你想过滤:

computed: {
filter_table() {
return this.links.filter(
(l) =>
l.tag.domain === this.filterTable["domainValue"] &&
l.post.indexed === this.filterTable["indexedValue"]
);
};

最新更新