javascript - 从 VUE.js 中的方法设置数据中的对象

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

    }
  }
});

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

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

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

最佳答案

问题出在这里:

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

希望这对您有所帮助。

关于javascript - 从 VUE.js 中的方法设置数据中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44869287/

相关文章:

javascript - 如何使用Chrome v8启动Node.js调试 session

javascript - vue.js 中的多个条件

javascript - Vue双向数据绑定(bind)问题

javascript - IE9 将上下文 'this' 转换为对象

javascript - 应用 onClick()、onMouseOver() 和 onMouseOut() 更改图像时出现问题

javascript - 当 header 中包含 Angular 时,模块 'tripSee' 不可用

vue.js - webpack vue cli 在重新加载时清除浏览器控制台

javascript - Vitest - FormData 不是测试单元的构造函数问题

mysql - GET http://localhost:3000/server/server.js net::ERR_ABORTED 404(未找到)

javascript - .put 在 Mocha Chai 请求中更新密码的方法不起作用