计算属性中的副作用

Side-effects-in-computed-properties

我想避免在我的代码中产生副作用,但我不知道如何解决这些问题,有人可以帮忙吗?

    computed: {
        sumarVerduras(){
          this.totalVerduras = 0;
            for( const verdura of this.verduras){
              this.totalVerduras = this.totalVerduras + verdura.cantidad
            } return this.totalVerduras;
        }
      }

效果如我所愿,但有副作用

Module Warning (from ./node_modules/eslint-loader/index.js):
error: Unexpected side effect in "sumarVerduras" computed property (vue/no-side-effects-in-computed-properties) at src\App.vue:53:7:
  51 |   computed: {
  52 |     sumarVerduras(){
  53 |       this.totalVerduras = 0;
     |       ^
  54 |         for( const verdura of this.verduras){
  55 |           this.totalVerduras = this.totalVerduras + verdura.cantidad
  56 |         } return this.totalVerduras;


error: Unexpected side effect in "sumarVerduras" computed property (vue/no-side-effects-in-computed-properties) at src\App.vue:55:11:
  53 |       this.totalVerduras = 0;
  54 |         for( const verdura of this.verduras){
  55 |           this.totalVerduras = this.totalVerduras + verdura.cantidad
     |           ^
  56 |         } return this.totalVerduras;
  57 |     }
  58 |   }

您不应在计算 属性 中编辑任何 Vue 组件的数据。这里修改了this.totalVerduras,算是Vue的组件数据。

您可以更改为:

computed: {
  sumarVerduras() {
    let totalVerduras = 0;
    for (const verdura of this.verduras) {
      totalVerduras = totalVerduras + verdura.cantidad
    } 
    return totalVerduras;
  }
}

你也可以这样做:

computed: {
  sumarVerduras() {
      return verduras.reduce((a, x) => a + x.cantidad, 0);
  }
}

此方法摆脱了 totalVerduras 变量和 for 循环。