2017-07-02 8 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

axios '.then()'メソッドのコールバック関数で 'this'の値が異なります。コールバックスコープで使用する前に、 'this'の値を外部に保存する必要があります。 – abhishekkannojia

+0

@abhishekkannojiaこれを 'app'に変更すると、それが私のVueインスタンスが定義されている方法で、' Can not undefinedまたはnullをオブジェクトに変換できません 'というエラーがスローされます。 – Svedr

+0

[Axiosでデータを設定できません]の重複している可能性があります(https://stackoverflow.com/questions/40996344/axios-cant-set-data) – yuriy636

答えて

2

問題はここにある:

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

あなたはコールバック・コンテキスト内であり、あなたはそれがあることを期待するかもしれないようthisの値はVueの対象ではありません。これを解決する1つの方法は、事前にthisの値を保存し、コールバック関数で使用することです。

Vue.set()を使用する代わりに、booksオブジェクトを直接更新してみてください。あなたが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(self.books, i, { 
    'title': item.title 
}); 

希望を。

+0

ご協力ありがとうございます。 「未定義またはnullをオブジェクトに変換できません」というエラーがまだ表示されています。 – Svedr

+0

@Svedrあなたのvue.setが間違っています。私は答えを編集します – abhishekkannojia

1

はい、問題は文脈です。 「これ」はあなたが返すと期待していないものを返します。

  1. あなたは

    自己を聞かせ=これを使用することができます。

  2. か、バインド

    関数(){} this.method .bind(本)を使用できます。

2番目の方法が優れています。

「jsでコンテキストを定義する方法」、「bind call apply js」のようなgoogleも、何がうまくいかないのか理解するのに役立ちます。

関連する問題