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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44869287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:46:12  来源:igfitidea点击:

Set object in data from a method in VUE.js

javascriptvue.js

提问by Svedr

I have been stuck with this issues for 2 hours now and I really can't seem to get it work.

我现在已经被这个问题困住了 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);
      });

    }
  }
});

When I initiate search and the API call I want the values to be passed to data so the final structure looks similar to the one below.

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

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

Currently I get Cannot read property '0' of undefined.

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

回答by abhishekkannojia

Problem lies here:

问题出在这里:

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

You are inside the callback context and the value of thisis not the Vue object as you might expect it to be. One way to solve this is to save the value of thisbeforehand and use it in the callback function.

您位于回调上下文中,并且 的值this不是您所期望的 Vue 对象。解决这个问题的一种方法是this预先保存 的值并在回调函数中使用它。

Also instead of using Vue.set(), try updating the books object directly.

另外,不要使用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);
      });

    }
  }
});

Or if you want to use Vue.set()then use this:

或者如果你想使用Vue.set()然后使用这个:

Vue.set(self.books, i, {
     'title': item.title
});

Hope this helps.

希望这可以帮助。

回答by Nikolay_R

yep, the problem is about context. "this" returns not what you expect it to return.

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

  1. you can use

    let self = this;

  2. or you can use bind

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

  1. 您可以使用

    让 self = this;

  2. 或者你可以使用绑定

    函数(){this.method}.bind(this);

the second method is better.

第二种方法更好。

Also google something like "how to define context in js", "bind call apply js" - it will help you to understand what is going wrong.

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