我一直堅持這個問題2個小時了,我真的不能得到它的工作。在VUE.js中的方法中設置數據對象
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
@abhishekkannojia如果我將它改爲'app',那就是我的Vue實例是如何定義的,它會拋出'不能將undefined或null轉換爲object'錯誤。 – Svedr
[Axios無法設置數據]的可能的重複(https://stackoverflow.com/questions/40996344/axios-cant-set-data) – yuriy636