【问题标题】:Vue lost reactivityVue 失去反应
【发布时间】:2019-02-26 09:25:44
【问题描述】:

不明白为什么这个简单的事情没有反应。 看起来我错过了一些 Vue 的基础。

<template>
    <div>
        {{connection_status}}
    </div>
</template>
<script>
export default {
    data() {
        return {
            connection_status: 'loading',
        };
    },
    created() {
        Echo.connector.socket.on('connect', function(){
            this.connection_status = 'connected'; 
            console.log(this.connection_status );   
        });
        Echo.connector.socket.on('disconnect', function(){
            this.connection_status = 'disconnected'; 
            console.log(this.connection_status );   
        });
    },  
}
</script> 

Echo 通过 socket.io 运行并且工作正常。所有事件都会及时触发。

连接时的控制台输出:

connected

但在页面上

loading

断开连接的触发器也是如此。 在控制台中:

disconnected

在页面上

loading

【问题讨论】:

    标签: javascript vue.js socket.io vuejs2 reactive-programming


    【解决方案1】:

    您的问题是回调函数中的this 没有引用Vue 实例。您应该改用箭头函数..

    created() {
            Echo.connector.socket.on('connect', ()=>{
                this.connection_status = 'connected';
                console.log(this.connection_status );   
            });
            Echo.connector.socket.on('disconnect', ()=>{
                this.connection_status = 'disconnected'; 
                console.log(this.connection_status );   
        });
    },
    

    或者您可以将this 分配给一个变量并在回调函数中使用它..

    created() {
            const vm = this;
            Echo.connector.socket.on('connect', function(){
                vm.connection_status = 'connected';
                console.log(vm.connection_status );   
            });
            Echo.connector.socket.on('disconnect', function(){
                vm.connection_status = 'disconnected'; 
                console.log(vm.connection_status );   
        });
    },
    

    【讨论】:

      【解决方案2】:

      在 javascript 中,函数是一个对象。使用function() {} 定义了一个新的对象范围,因此为this 定义了一个新的范围。您将值分配给 function 上的 connection_status 属性,而不是您的 vue 组件。

      最好的做法是使用箭头函数,除非你需要一个新的函数作用域,因为箭头函数从它们定义的作用域继承this

      Echo.connector.socket.on('connect', () => {
          this.connection_status = 'connected'; 
          console.log(this.connection_status );   
      });
      Echo.connector.socket.on('disconnect', () => {
          this.connection_status = 'disconnected'; 
          console.log(this.connection_status );   
      });
      

      【讨论】:

        【解决方案3】:

        如果我很好地理解文档,您应该使用 mount() 钩子而不是 created() 钩子:https://vuejs.org/v2/api/#created

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-03-16
          • 2021-03-15
          • 1970-01-01
          • 2023-04-05
          • 2021-10-04
          • 2018-11-08
          • 2017-08-06
          • 1970-01-01
          相关资源
          最近更新 更多