gpt4 book ai didi

javascript - Vue 失去 react 性

转载 作者:行者123 更新时间:2023-11-28 17:09:23 29 4
gpt4 key购买 nike

无法理解为什么这个简单的事情没有反应性。看起来我错过了一些 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

最佳答案

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

关于javascript - Vue 失去 react 性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54882179/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com