vue优化之少用this去读取data中数据

在计算属性和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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值