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

    }
  }
});

当我启动搜索和 API 调用时,我希望将值传递给数据,以便最终结构类似于下面的结构。

 data: {
  searchInput: '',
  books: {
    "0": {
       title: "Book 1"
     },
    "1": {
       title: "Book 2"
     }
},

目前我得到 Cannot read property '0' of undefined

原文由 Svedr 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 337
2 个回答

问题出在这里:

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

希望这可以帮助。

原文由 abhishekkannojia 发布,翻译遵循 CC BY-SA 3.0 许可协议

是的,问题在于上下文。 “this”返回的不是您期望它返回的内容。

  1. 您可以使用

让自我=这个;

  1. 或者你可以使用绑定

function(){this.method}.bind(this);

第二种方法更好。

也谷歌诸如“如何在 js 中定义上下文”、“绑定调用应用 js”之类的东西——它会帮助你理解出了什么问题。

原文由 Mykola Riabchenko 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题