【问题标题】:VUE.JS/HTTP. The problem with getting a result of http query to an html using vue.jsVUE.JS/HTTP。使用 vue.js 将 http 查询结果获取到 html 的问题
【发布时间】:2019-07-08 19:17:18
【问题描述】:

我正在尝试制作一个简单的应用程序,以使用 Vue.js 将来自 https://docs.coincap.io 的 API 调用输出到 HTML 表中,因为我需要添加一些其他功能。

问题是,我无法使用 v-for 和 mustache 将对象数组放入页面以检查变量数据。

我尝试使用 vue 生命周期钩子将我的 API 调用数据放入一个变量中,并在不同的地方将我的数据放入一个对象数组中。

<div id="app">
    TEST APPLICATION FOR COINCAP  <br>

    <div id="xhrRes">
      {{ items }}
    </div>

    <table class="table-o">
      <tr class="table-o__head">
        <th class="table-o__rank">Rank</th>
        <th>Name</th>
        <th>Price</th>
        <th>Market Cap</th>
        <th>Volume</th>
        <th>Change</th>
      </tr>
      <tr v-for="(item, index) in items">
        <td>
          {{ index }}
        </td>
        <td>
          {{ item.name }}
        </td>
        <td>
          {{ item.price }}
        </td>
        <td>
          {{ item.marketCapUsd }}
        </td>
        <td>
          {{ item.volumeUsd24Hr }}
        </td>
        <td>
          {{ item.changePercent24Hr }}
        </td>
      </tr>
    </table>
  </div>



export default {
  name: 'app',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App',
      xhrUri: 'https://api.coincap.io/v2/assets?limit=15',
      xhrResult: '',
      items: []
    }
  },
  updated() {
    // this.items = this.xhrRequest();
    this.xhrRequest();
    // console.log(this.items);
  },
  methods: {
    xhrRequest: function() {
      let xhr = new XMLHttpRequest();

      xhr.open('GET', this.xhrUri, true);
      xhr.send();

      xhr.onreadystatechange = function() {
        if (xhr.readyState != 4) {
          return;
        }

        if (xhr.status === 200) {
          this.items = JSON.parse(xhr.responseText).data;
          console.log(this.items);
        } else {
          console.log('err', xhr.responseText)
        }

      }
    }
  }
}

我希望在 {{ items }} 中有一个对象数组和一个已填充的表,但我的对象数组未定义并且我的表为空

【问题讨论】:

    标签: javascript http vue.js xmlhttprequest


    【解决方案1】:

    我建议使用created 挂钩而不是updated

    更大的问题是xhr.onreadystatechange 中的this 上下文。它不会指向 Vue 实例。使用箭头函数是最简单的解决方法:

    xhr.onreadystatechange = () => {
    

    箭头函数保留周围作用域中的this 值。

    通常的替代方案也适用,例如在函数上使用bind 或使用const that = this 在闭包中获取this。 Vue 自动将 methods 中的函数绑定到正确的 this 值,因此如果您引入另一种方法作为 onreadystatechange 的处理程序,它也可以工作。

    【讨论】:

    • 效果很好,我忘记了“this”的上下文。
    猜你喜欢
    • 2018-12-06
    • 2018-07-31
    • 2018-06-04
    • 2018-09-15
    • 1970-01-01
    • 2016-05-14
    • 2018-06-28
    • 2018-06-30
    • 1970-01-01
    相关资源
    最近更新 更多