【发布时间】:2017-12-05 18:16:12
【问题描述】:
我已经被这个问题困扰了 2 个小时,我似乎真的无法让它工作。
const app = new Vue({
el: '#book-search',
data: {
searchInput: 'a',
books: {},
},
methods: {
foo: function () {
axios.get('https://www.googleapis.com/books/v1/volumes', {
params: {
q: this.searchInput
}
})
.then(function (response) {
var items = response.data.items
for (i = 0; i < items.length; i++) {
var item = items[i].volumeInfo;
Vue.set(this.books[i], 'title', item.title);
}
})
.catch(function (error) {
console.log(error);
});
}
}
});
当我启动搜索和 API 调用时,我希望将值传递给数据,以便最终结构类似于下面的结构。
data: {
searchInput: '',
books: {
"0": {
title: "Book 1"
},
"1": {
title: "Book 2"
}
},
目前我收到Cannot read property '0' of undefined。
【问题讨论】:
-
this的值在axios.then()方法的回调函数中不同。在回调范围内使用之前,您必须将this的值保存在外部。 -
@abhishekkannojia 如果我将其更改为
app,这就是我的 Vue 实例的定义方式,它会引发Cannot convert undefined or null to object错误。 -
Axios can't set data的可能重复
-
请注意,这是关于“传统”JavaScript 对象(字典),而不是使用
new Set()创建的实际Set对象 - 我来这里是为了了解 Vue 如何处理这些...跨度>
标签: javascript vue.js