【问题标题】:Vue is not Firing on Json Update for the second timeVue 第二次没有在 Json 更新上触发
【发布时间】:2021-04-28 21:37:55
【问题描述】:

我是 Vue.js 的新手。在这里,我试图实现从我的 Restful api 返回的一些 JSON 对象的渲染。当我从某个控件调用 allListing(streamid) 时,我需要呈现从 API 接收到的更改后的 JSON。玩了一整天,想来这里问问。

提前致谢。

callListing(1);

function callListing(streamid) {
  var vm = new Vue({
    el: '#app',
    data() {
      return {
        info: []

      }
    },
    created() {
      axios
        .get('https://localhost:44367/api/listing_institution/byselector/t/' + streamid + '/1')
        .then(response => {
          this.info = response.data,
            console.log(response);

        })
    }
  })
}

function fireListing(streamid) {
  callListing(streamid);
}
<div id="app">
  <div v-for="dt in info">
    {{dt}}
  </div>
</div>

【问题讨论】:

  • 控件在哪里?应用外部?

标签: json vue.js axios


【解决方案1】:

你应该使用 Vue.set 来让你的数据反应。

Vue.set 是一个工具,它允许我们向已经反应的对象添加新属性。阅读更多关于 Vue.set here.

因此,您只需对代码进行很少的修复。

而不是-

this.info = response.data,

喜欢-

Vue.set(this.info, 0, response.data);

// It takes three params-
//   1. The element inside which we want to update
//   2. The index where we want to put updated response.
//   3. Response

您可以查看此示例以供参考- CodeSandBox example

【讨论】:

  • 如果他打算从 api 中检索一个数组,set 是没有用的。在这种情况下,将数据直接设置为this.info 是最有意义的。它将反应性地替换空数组。
  • 是的,同意,但是因为他每次都试图通过从某个未更新的控件向函数传递一个 id 来更新 JSON,所以在这种情况下 set 会很有帮助。如果他正在尝试更新整个数组,则不应出现问题(正如您所说的那样。)
猜你喜欢
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 2015-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多