在VUE.js中的方法中设置数据中的对象

Sve*_*edr 3 javascript vue.js

我现在已经坚持这个问题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);
      });

    }
  }
});
Run Code Online (Sandbox Code Playgroud)

当我启动搜索和API调用时,我希望将值传递给数据,因此最终结构看起来类似于下面的结构.

data: {
  searchInput: '',
  books: {
    "0": {
       title: "Book 1"
     },
    "1": {
       title: "Book 2"
     }
},
Run Code Online (Sandbox Code Playgroud)

目前我明白了Cannot read property '0' of undefined.

abh*_*jia 9

问题出在这里:

Vue.set(this.books[i], 'title', item.title);
Run Code Online (Sandbox Code Playgroud)

您处于回调上下文中,并且值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);
      });

    }
  }
});
Run Code Online (Sandbox Code Playgroud)

或者如果你想使用,Vue.set()那么使用这个:

Vue.set(self.books, i, {
     'title': item.title
});
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.