我试图把进度微调器放在数据加载上。用户单击html按钮,然后执行以下功能。阵列过滤器可能需要一些时间,具体取决于阵列大小。我希望变量isLoading在开始时为true,在过滤器功能完成时为false。变量isLoading用于显示/隐藏进度微调器。
myfunction(val){
this.isLoading = true
var data = this.myarray.filter(function(item) {
// this.isLoading = false // tried this, throws error - Cannot set property 'isLoading' of undefined
return item.name == val;
});
this.showdata = data[0]
// this.isLoading = false // tried this, but this does not show effect
}
请提出建议,如何处理。 谢谢
This is happening because functions in JavaScript has their own context, meaning
this
inside the function that does the filtering is different than the one inside themyfunction
.要将上下文传递给另一个函数,可以使用bind。
另外,如果您的环境支持ES6或使用babel,则可以使用箭头功能代替:
Filter is not an asynchronous method, your program will wait till its completion. You simply have to remove the
this.isLoading = false
from inside the filter:this
has a different context inside the function, and is not the same as that object referred to by the outerthis