在计算属性上启用输入字段的加载状态



编辑:代码笔被添加在文章末尾

如何启用(更改为true)在一个计算属性的输入字段的加载?

在接下来的演示示例中,我得到'error'unexpected side effect in "inputFilterParentsAndChilds" computed property.

搜索字段和列表

<template>
<q-input
label="Search"
v-model="searchValue"
placeholder="Minimum 3 characters"
:loading="loadingState"
/>
<q-list
v-for="pater in inputFilterParentsAndChilds"
:key="pater.id_parent"
>
<q-item>
<q-item-section>
<q-item-label>
{{ pater.name }}
</q-item-label>
</q-item-section>
</q-item>
<q-list
v-for="filius in pater.allfilius"
:key="filius.id_filius"
>
<q-item>
<q-item-section>
<q-item-label>
{{ filius.title }}
</q-item-label>
</q-item-section>
</q-item>
</q-list>
</q-list>
</template>

计算规范

<script>
export default {
data() {
return {
loadingState: false,
searchValue: ''
};
}
}
computed: {
//filter the parent list with nested data (childs)
inputFilterParentsAndChilds() {
if (this.searchValue.length > 2) {
this.loadingState = true; // error!! unexpected side effect in "inputFilterParentsAndChilds" computed property
const filteredPaterArr = this.records.map((rows) => {          
const filteredParent = rows.filius.filter(
({ name }) =>
name.toLowerCase().match(this.searchValue.toLowerCase())
);
const filteredChilds = rows.filius.filter(
({ title }) =>
title.toLowerCase().match(this.searchValue.toLowerCase())
);
if (filteredChilds.length) {
this.loadingState = false;
return { ...rows, filius: filteredParent };
} else {
this.loadingState = false;
return { ...rows, filius: filteredChilds };
}
});
return filteredPaterArr.filter((obj) => obj.filius.length);
} else {
return this.records;
}      
}
}
</script>

关于嵌套v-for列表

编辑CODEPEN https://codepen.io/ijose/pen/BaYMVrO

为什么加载在我的情况下很重要?

如果列表有数百条记录,则过滤器速度很慢,并且看起来(错误地)已经冻结,需要加载以通知用户过滤操作仍在进行中

你不能,计算属性根本不能改变状态。

您可以通过监视searchValue来实现类似的效果。

data () {
return {
searchValue: '',
isLoading: false,
filteredElements: []
}
},
watch: {
searchValue: {
immediate: true, // tells Vue to run handler function right after constructing the component
handler () {
// this function will be triggered when searchValue changes
this.isLoading = true
// give Vue chance to render the loader before doing heavy computation in 'filterElements' function
this.$nextTick(() => {
this.filteredElements = this.filterElements()
this.isLoading = false
})
}
}

Docs on nextTick

编辑:您是否测量过,真正是计算使下拉菜单变慢,而不是渲染?查看一下有关性能的文档,特别是"虚拟化大型列表">

最新更新