我正在尝试制作一个简单的应用程序,使用 Vue.js 将 API 调用从 https://docs.coincap.io 输出到 HTML 表中,因为我需要添加一些其他功能。
问题是,我无法使用 v-for 和 moustache 将我的对象数组放入页面中以检查变量数据。
我尝试使用 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 }} 中有一个对象数组和一个填充的表,但未定义我的对象数组并且我的表为空
我建议使用 created
钩子而不是 updated
.
更大的问题是xhr.onreadystatechange
内部的this
语境。它不会指向 Vue 实例。使用箭头函数是最简单的解决方法:
xhr.onreadystatechange = () => {
箭头函数保留周围范围内的this
值。
通常的替代方案也适用,例如在函数上使用bind
或使用const that = this
在闭包中抓取this
。Vue 会自动将methods
中的函数绑定到正确的this
值,因此如果您引入了另一种方法作为onreadystatechange
的处理程序,那也将起作用。