在计算属性和template模板中滥用this去读取data中数据会导致多次重复地收集依赖,从而产生性能问题,那要怎么避免这种情况。
计算属性中如何避免
用ES6对象解构赋值来避免,计算属性的值是一个函数,其参数是Vue的实例化this对象,在上述计算属性中滥用this的例子中可以这样优化。
优化前:
computed:{
d:function(){
let result = 0;
for(let key in this.a){
if(this.a[key].num > 20){
result += this.a[key].num + this.b + this.c;
}else{
result += this.a[key].num + this.e + this.f;
}
}
return result;
}
}
优化后:
computed: {
d({ a, b, c, e, f }) {
let result = 0;
for (let key in a) {
if (a[key].num > 20) {
result += a[key].num + b + c;
} else {
result += a[key].num + e + f;
}
}
return result;
}
}
template模板中如何避免
提前处理v-for循环所用的数据,不要在v-for循环中去读取数组、对象类型的数据。在上述template模板中滥用this的例子中可以这样优化。
假设list、arr、obj皆是服务端返回来的数据,且arr和obj没有用到任何模块渲染中,可以这样优化。
优化前:
<template>
<div class="wrap">
<div v-for=item in list>
<div> {{ arr[item.index]['name'] }} </div>
<div> {{ obj[item.id]['age'] }} </div>
</div>
</div>
</template>
优化后:
<template>
<div class="wrap">
<div v-for=item in listData>
<div{{item.name}} </div>
<div>{{item.age}}</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
list: [],
}
},
created(){
// 在这里定义arr和obj避免被转成响应式
this.arr = [];
this.obj = {};
},
computed: {
listData: function ({list}) {
list.forEach(item => {
item.name = this.arr[item.index].name;
item.age = this.obj[item.id].age;
})
return list;
}
},
}
</script>