javascript - 从套接字接收消息时Vue.js数据不更新
问题描述
我正在尝试设计一个 vue.js 应用程序,该应用程序在从套接字接收到“new_state”消息时更新有关游戏状态的数据。套接字是使用 django 通道实现的。
这是代码的样子:
const ws_scheme = window.location.protocol == "https:" ? "wss" : "ws"
const gameSocket = new WebSocket(
ws_scheme +
'://'
+ window.location.host
+ '/ws/play/'
+ game_id
+ '/'
)
let vue = new Vue({
el: '#app',
data: {
current_turn: 0,
last_turn: -1,
current_card: 0,
last_card: -1,
number_of_stacked_cards: 0,
last_amount_played: 0,
won_by: -1,
my_cards: [],
other_players_data: {},
},
created() {
gameSocket.onmessage = function(e) {
data = JSON.parse(e.data)
this.current_turn = data.state.current_turn
this.last_turn = data.state.last_turn
// ... update the other data
};
},
});
当我收到消息时,记录数据表明我收到了正确的信息。但是,如果我vue.current_turn
在收到消息后去输入,它仍然0
不是新值;对象的所有其他成员都相同data
。我试过了vue.current_turn = data.state.current_turn
,它确实以这种方式工作,但显然它应该与this
.
我的代码有什么问题?
一般来说,完成我所追求的最佳方式是什么,即在从套接字接收消息时更新内部数据变量?
我必须不使用 socket.io 库,频道不支持该库。
解决方案
问题是this
指向任何调用gameSocket.onmessage
,而不是“正常的 Vue this
”。
为了解决这个问题,您可以在let self = this
上面执行gameSocket.onmessage
并self
在其中使用。
推荐阅读
- mysql - 使用 Group By MySQL 连接 3 个表
- go - 去测试验证 connect2id 给出“invalid_client”错误
- android - android中自动完成文本视图内的动态表格布局
- javascript - 从数组中过滤值
- audio-streaming - Agora 音频广播事件回调
- google-cloud-firestore - 从云函数获取用户的uid
- javascript - 后退按钮重定向脚本问题
- javascript - 根据 2 个单独的字段查找文档的最新日期:月份和年份
- android - 在进度条可见时使用户交互处于非活动状态
- git-bash - 通过 Windows 终端中的脚本设置 git bash 配色方案