【问题标题】:socket.io and vue.js fetching datasocket.io 和 vue.js 获取数据
【发布时间】:2017-03-18 19:33:14
【问题描述】:

我正在尝试使用这个来获取 vue.js 的数据

fetchData: function () {
                socket.emit('getAllSongs')
                socket.on('allSongs',function(data) {
                    this.songs = data
                });

          }

在创建 vue 应用时调用 FetchData

created: function () {
            this.fetchData();
        }

但是当我尝试在 socket.on 之外调用变量 songs 时,它仍然是空的。

我能做什么?

【问题讨论】:

  • this.songs value of this 在这种情况下是不同的,这不是您所期望的,一种快速的解决方法是将 this 的值保存在函数之外然后使用它。
  • 如何引用正确的“歌曲”?我试图在 socket.on 中调用一个函数来做到这一点,但它找不到该函数。我现在有点迷茫

标签: javascript node.js function sockets vue.js


【解决方案1】:

尝试将fetchData 函数更改为:

fetchData: function () {
    socket.emit('getAllSongs')
    var that = this;
    socket.on('allSongs',function(data) {
        that.songs = data
    });
}

原因是 this 在回调上下文中的值不同,并且不是您期望的组件对象。

【讨论】:

    【解决方案2】:

    我认为您需要将此绑定到函数的末尾或使用 ES6 箭头语法=>

    socket.on('allSongs',function(data) {
        that.songs = data
    }.bind(this));
    
    socket.on('allSongs',data => {
        that.songs = data
    });
    

    【讨论】:

      猜你喜欢
      • 2018-09-09
      • 1970-01-01
      • 2015-12-05
      • 2020-01-21
      • 2016-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-24
      相关资源
      最近更新 更多