我正在尝试设计一个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库的情况下进行处理,该库不受通道支持。
答案 0 :(得分:1)
问题在于this
指向的是任何调用gameSocket.onmessage
,而不是“普通Vue this
”。
要解决此问题,您可以在let self = this
上方进行gameSocket.onmessage
,并在其中使用self
。