我试图从我的组件的挂载方法访问我的商店数据。如果我用未安装的方法尝试它,它工作正常。在我读了一下之后,我没有访问权限,但还有其他方法我还没有找到吗?
methods: {
testEvent() {
// works
let players = this.$store.state.players;
console.log(players);
},
socketEvent() {
// Uncaught TypeError: Cannot read property 'state' of undefined
socket.on('dice_data', function(data) {
let players = this.$store.state.players;
console.log(players);
});
}
},
mounted() {
this.socketEvent()
}
谢谢
答案 0 :(得分:2)
问题在于功能
中的此你可以这样解决:
socketEvent() {
socket.on('dice_data', (data) => {
let players = this.$store.state.players;
console.log(players);
});
}
或者如果您更喜欢编写函数,而不是箭头函数,您也可以这样做:
socketEvent() {
let self = this
socket.on('dice_data', function(data) {
let players = self.$store.state.players;
console.log(players);
});
}