【问题标题】:Is it possible with Vue.js to create a computed property whose value can be changed directly?Vue.js 是否可以创建一个可以直接更改其值的计算属性?
【发布时间】:2019-12-11 11:03:24
【问题描述】:

最初安装组件时,我的计算属性从存储操作(其中包含 axios 调用)接收信息。但是我需要稍后直接更改它的值:

myComputedProperty: {
  get: function () {
    return this.myStoreActionResult;
  },
  set: function (newValue) {
    return newValue
  }
}

但是,使用此设置,我无法更改其值:

console.log(this.myComputedProperty)
this.myComputedProperty = 'new value!'
console.log(this.myComputedProperty)

我希望这会显示初始值(基于商店信息),然后显示新值。相反,它显示两倍的初始值:我无法直接更改计算属性的值。

有没有办法做到这一点,如果有,怎么做?

【问题讨论】:

  • 为什么会这样?您实际上并没有在 set 中设置任何内容
  • 是的,我知道,但我不知道该怎么做,所以我只是把 return newValue 更像是一个占位符,我猜

标签: vue.js computed-properties


【解决方案1】:

计算属性用于返回计算(和缓存)的值,因此您不能直接设置它的值,因为它根本不存在。计算属性后面是您可以使用 setter 设置的变量,就像在您的示例中一样。您只需要设置引用变量的新值:

myComputedProperty: {
  get: function () {
    return this.myStoreActionResult;
  },
  set: function (newValue) {
    this.myStoreActionResult = newValue;
    return newValue
  }
}

像上面的例子那样使用计算变量是没有用的,因为你间接修改了原始属性。

【讨论】:

    【解决方案2】:

    是的,这是可能的。

    请参阅此处的 Vue.js 文档:Computed Setter

    你的代码会变成这样:

    myComputedProperty: {
      get: function () {
        return this.myStoreActionResult;
      },
      set: function (newValue) {
        this.myStoreActionResult = newVaue;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-26
      • 2019-08-07
      • 2011-12-18
      • 1970-01-01
      相关资源
      最近更新 更多