我已经被这个问题困扰了 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
。
最佳答案
问题出在这里:
Vue.set(this.books[i], 'title', item.title);
您处于回调上下文中,this
的值不是您可能期望的 Vue 对象。解决这个问题的一种方法是预先保存 this
的值并在回调函数中使用它。
另外,不要使用 Vue.set()
,尝试直接更新 books 对象。
const app = new Vue({
el: '#book-search',
data: {
searchInput: 'a',
books: {},
},
methods: {
foo: function () {
var self = this;
//--^^^^^^^^^^^^ Save this
axios.get('https://www.googleapis.com/books/v1/volumes', {
params: {
q: self.searchInput
//-^^^^--- use self instead of this
}
})
.then(function (response) {
var items = response.data.items
var books = {};
for (i = 0; i < items.length; i++) {
var item = items[i].volumeInfo;
books[i] = { 'title' : item.title };
}
self.books = books;
})
.catch(function (error) {
console.log(error);
});
}
}
});
或者如果你想使用 Vue.set()
然后使用这个:
Vue.set(self.books, i, {
'title': item.title
});
希望这对您有所帮助。
关于javascript - 从 VUE.js 中的方法设置数据中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44869287/