【问题标题】:Vue fetch response.json promise not creating reactive gettersVue fetch response.json 承诺不会创建响应式 getter
【发布时间】:2017-09-13 06:38:14
【问题描述】:

我有一个用 Typescript 编写的 Vue 应用程序,我正在使用 Fetch 从 api 检索数据。在我的一个组件中,我定义了以下接口:

interface SearchResult {
    device_id: string;
    location: string;
    sub_location: string;
    status: string;
}

在我的 Fetch 方法中,我将 response.json() 承诺转换为 SearchResult 接口的数组,如下所示:

fetch(url).then(response => response.json() as Promise<SearchResult[]>)
          .then(data => { 
              this.results = data; 
          })

我遇到的问题是,如果 response.json() 中不包含“状态”,则不会为 this.results.status 创建响应式 getter,这意味着我无法改变数据并让它在页面上做出反应。

我尝试在this.results = data 行之后手动设置“状态”的值,当我使用 VueTools 检查对象时,我可以看到它具有我分配的值的状态属性。但是反应式 getter 和 setter 仍然缺失。

我还尝试将接口更改为具有为“状态”设置默认值的构造函数的类,但这也未能为属性创建反应式 getter 和 setter。

如何在不向 api 响应显式添加“状态”(或任何其他任意属性)的情况下创建反应式 getter 和 setter?

【问题讨论】:

    标签: json typescript vuejs2 fetch-api


    【解决方案1】:

    Vue cannot detect 属性添加到已添加到数据的对象中,除非您通过 $set 添加属性。

    将您的获取响应更改为:

    fetch(url)
      .then(response => response.json() as Promise<SearchResult[]>)
      .then(data => { 
        this.results = data; 
        for (let result of this.results)
          this.$set(result, 'status', "some value");
      })
    

    虽然你也应该能够逃脱:

    fetch(url)
      .then(response => response.json() as Promise<SearchResult[]>)
      .then(data => { 
        this.results = data.map(d => d.status = "some value"); 
      })
    

    【讨论】:

    • 我最终使用的解决方案是第二个建议。因为data 是一个数组,所以在对其进行迭代时设置属性然后将其设置为this.results 会更容易。关键是在将data 对象分配给this.results 之前设置其属性。
    • @hackintosh Doh,对不起,我没有注意到它是一个数组。相当明显。我更新了答案。
    猜你喜欢
    • 1970-01-01
    • 2013-09-15
    • 1970-01-01
    • 2017-02-08
    • 2021-01-28
    • 2021-04-11
    • 2020-04-18
    • 2021-12-24
    • 1970-01-01
    相关资源
    最近更新 更多