Vue失去反应性

时间:2019-02-26 09:25:45

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

不明白为什么这种简单的事情没有反应性。 似乎我错过了一些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

3 个答案:

答案 0 :(得分:2)

您的问题是,回调函数中的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 );   
    });
},

答案 1 :(得分:1)

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

答案 2 :(得分:0)

如果我对doc非常了解,则应该使用mount()钩子而不是created()钩子:https://vuejs.org/v2/api/#created