2017-07-02 52 views
1

我一直堅持這個問題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

+0

'this'的值在axios'.then()'方法的回調函數中不同。在回調範圍內使用之前,必須將「this」的值保存到外部。 – abhishekkannojia

+0

@abhishekkannojia如果我將它改爲'app',那就是我的Vue實例是如何定義的,它會拋出'不能將undefined或null轉換爲object'錯誤。 – Svedr

+0

[Axios無法設置數據]的可能的重複(https://stackoverflow.com/questions/40996344/axios-cant-set-data) – yuriy636

回答

2

問題就在這裏:

Vue.set(this.books[i], 'title', item.title); 

您是回調的上下文中和this值不是Vue的對象,你可能會希望它是。解決這個問題的一種方法是預先保存this的值並在回調函數中使用它。

而不是使用Vue.set(),請嘗試直接更新書籍對象。

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 
}); 

希望這有助於。

+0

嘿,感謝您的幫助,這很有道理,但我我仍然得到'不能將undefined或null轉換爲object'錯誤。 – Svedr

+0

@Svedr你的vue.set是錯誤的。我會編輯答案 – abhishekkannojia

1

是的,問題是關於上下文。 「這個」不會返回你期望的結果。

  1. 可以使用

    讓自我=這一點;

  2. 或可以使用綁定

    函數(){} this.method .bind(本);

第二種方法比較好。

另外谷歌的東西,如「如何在js中定義上下文」,「綁定調用應用js」 - 它會幫助您瞭解發生了什麼問題。

相關問題