【问题标题】:Why Am I getting error return in computed property?为什么我在计算属性中得到错误返回?
【发布时间】:2021-05-19 23:03:32
【问题描述】:

我正在使用Vuex,在Getter Foo function 内部我在数组中返回两个值:

return ["Try Again"]return ["Data result", data],在计算中,我正在检查 array length 并根据结果返回

  computed:{    
    Foo: function(){
      const getFoo =  this.$store.getters.Foo;
      if(getFoo.length === 1) {
        this.existFoo = false
        return getFoo[0]
      }
      this.existFoo = true
      return getFoo
    }
  }

但是我遇到了这个错误,即使阅读其他帖子我也无法解决它

34:9 错误“Foo”计算属性中的意外副作用 vue/计算属性中的无副作用
37:7 错误意外 “Foo”计算属性的副作用 vue/no-side-effects-in-computed-properties

【问题讨论】:

标签: vue.js vuex


【解决方案1】:

您不能更改计算中的状态。 尝试使用另一个计算而不是existFoo

  computed:{        
    Foo(){
      if(this.$store.getters.Foo.length === 1) {
        return this.$store.getters.Foo[0]
      }          
      return this.$store.getters.Foo
    },
    existFoo(){
        return this.$store.getters.Foo.length > 1
    }
  }

现在您应该从 state 中删除 existFoo

【讨论】:

    【解决方案2】:

    您可以使用观察器来观察存储值并设置您的局部变量。

    computed: {
      getFooFromStore() {
        return this.$store.getters.Foo
      }
    }
    
    watch: {
      getFooFromStore: function() {
        this.existFoo = this.getFooFromStore[0] ? false : true;
      }
    }

    【讨论】:

    • 我没有考虑过,一旦我需要访问data (){ existFoo } 并通过computed function 是不可能的,对吧?
    • 对不起,我不完全理解你的问题。您可以在计算属性中访问数据变量,但如果这就是您的意思,则不能在计算属性中设置它们。
    • 是的,我无法从计算属性访问,但使用监视属性可以设置任何条件
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    • 2012-01-10
    • 1970-01-01
    相关资源
    最近更新 更多