【问题标题】:Vue computed property not updatingVue计算属性未更新
【发布时间】:2019-10-03 19:29:55
【问题描述】:

我有一个空的对象数据属性

data() {
  return {
    chosen: {},
  }
}

然后我有一个计算属性,其结果与所选属性相关。

myComputed() {
  let result = 0
  Object.entries(this.chosen).forEach(([key, value]) => {
    result = result + value
  })
  return result

}

然后我有一个方法可以实际更改所选属性

setChosen(someValue) {
  this.chosen['key'] = someValue
}

所以当我调用 setChosen 并添加一个新值时,myComputed 不会执行,也不会更新我的视图值。

【问题讨论】:

  • 您正在尝试在计算方法中将对象属性作为数组属性访问

标签: vue.js


【解决方案1】:

我认为这是由于您的计算方法未检测到更改造成的,请在此处阅读更多信息:https://vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats

试试以下方法:

setChosen(someValue) {
    // IF no key is parsed
    this.$set(this.chosen, 'key', someValue)

    // IF key is parsed
    // this.$set(this.chosen, key, someValue)

}

显然,如果 someValue 只是值,则需要将“key”括在引号中以直接命名:key。如果您的函数被解析为字符串的第二个值,则直接使用它。

被动设置新值

【讨论】:

    猜你喜欢
    • 2018-03-05
    • 1970-01-01
    • 2018-05-03
    • 2019-05-05
    • 2019-10-19
    • 1970-01-01
    • 2019-04-18
    • 2021-03-20
    相关资源
    最近更新 更多