【问题标题】:Change vue data from promise callback从 Promise 回调中更改 Vue 数据
【发布时间】:2018-11-09 05:06:08
【问题描述】:

我正在尝试从 Promise 回调中更改我的 Vue 数据, 并且由于某种原因,我看不到模板中的值变化,

我看到了这个问题how to update a vue's property in a promise call back? 我已将this 更改为正确的,但我仍然看不到模板中的值发生变化。

这是我的模板:

<template>
  {{ sites }}
</template>

这是我的脚本:

data: () => ({
  sites: {}
}),
methods: {
  initialize(snapshot) {
    let _this = this
    snapshot.forEach((site) => {
      convert(site.data())
        .then(converted => {
          _this.sites[site.id] = converted
        })
    })
  }
}

知道为什么我的数据不会改变吗?

【问题讨论】:

  • 那里有什么转换?
  • 这是一个异步函数,可将所有 firestore DocumentReference 转换为 JSON:stackoverflow.com/questions/50597797/…
  • 您确定 convert 没有拒绝承诺(then 回调中的 console.log(converted) 实际上输出了您期望的内容)吗?
  • 是的,确实如此……

标签: javascript vue.js vuejs2


【解决方案1】:

我认为这是反应性问题。请尝试

.then(converted => {
  const sites = JSON.parse(JSON.stringify(_this.sites))
  sites[site.id] = converted
  _this.sites = sites
}

更多解释:

为了更新页面,Vue 进行了廉价的比较(据我了解,参考比较)。如果只更新对象的属性,它们仍然指向相同的引用 -> Vue 不会更新页面。所以我们需要对它们进行深拷贝以进行比较

【讨论】:

  • 工作得很好,你能解释一下这个主题,或者参考一些文件吗?
  • 看看Vue.js Array caveats。还有记录表明您可以使用Vue.$setArray.prototype.splice 来检测更改。
猜你喜欢
  • 1970-01-01
  • 2018-05-30
  • 1970-01-01
  • 2018-04-07
  • 1970-01-01
  • 2019-02-14
  • 2020-05-21
  • 2020-05-18
  • 2020-04-03
相关资源
最近更新 更多