【问题标题】:Set object in data from a method in VUE.js从 VUE.js 中的方法设置数据中的对象
【发布时间】:2017-12-05 18:16:12
【问题描述】:

我已经被这个问题困扰了 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

【问题讨论】:

  • this的值在axios .then()方法的回调函数中不同。在回调范围内使用之前,您必须将 this 的值保存在外部。
  • @abhishekkannojia 如果我将其更改为 app,这就是我的 Vue 实例的定义方式,它会引发 Cannot convert undefined or null to object 错误。
  • Axios can't set data的可能重复
  • 请注意,这是关于“传统”JavaScript 对象(字典),而不是使用 new Set() 创建的实际 Set 对象 - 我来这里是为了了解 Vue 如何处理这些...跨度>

标签: javascript vue.js


【解决方案1】:

问题出在这里:

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

希望这会有所帮助。

【讨论】:

  • 嘿,感谢您的帮助,这很有意义,但我仍然收到 Cannot convert undefined or null to object 错误。
  • 这对我有帮助。谢谢。
【解决方案2】:

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

  1. 你可以使用

    让 self = this;

  2. 或者你可以使用绑定

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

第二种方法更好。

还可以在 Google 上搜索“如何在 js 中定义上下文”、“绑定调用应用 js”之类的内容 - 这将帮助您了解发生了什么问题。

【讨论】:

    【解决方案3】:
    // update component's data with some object's fields
    // bad idea, use at your own risk
    
    Object
      .keys(patch)
      .forEach(key => this.$data[key] = patch[key])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-30
      相关资源
      最近更新 更多