【发布时间】:2020-09-12 19:36:43
【问题描述】:
我刚开始研究 Vue 和 Vuex。我在 Vuex 中创建了一个带有状态数据的组件。一个动作之后,我可以看到我的状态更改应用到了变异中,但是,我的 Vue 组件仍然无法拾取新的更改。
这是我的商店文件:
const state = {
roomInfo: {
gameID: null,
userID: null,
},
seats: null,
};
const getters = {
seats: state => state.seats,
roomInfo: state => state.roomInfo,
};
const actions = {
async streamSeats({ commit }) {
let connection = new WebSocket(`ws://localhost:8080/api/game/${state.roomInfo.gameID}/seats/${state.roomInfo.userID}`)
connection.onmessage = function(event) {
commit('setSeats', event.data);
}
connection.onopen = function() {
console.log("Successfully connected to the echo websocket server...")
}
connection.onerror = function(event) {
console.log("ERRR", event)
}
},
async setRoomInfo({ commit }, roomInfo) {
commit('setRoomInfo', roomInfo);
},
};
const mutations = {
setSeats: (state, seats) => {
state.seats = seats
// I can see changes here properly
console.log(seats);
},
setRoomInfo: (state, roomInfo) => {
state.roomInfo.gameID = roomInfo.gameID;
state.roomInfo.userID = roomInfo.userID;
if (roomInfo.seatNumber === 1) {
state.seats.p1.id = roomInfo.userID;
}
},
};
export default {
state,
getters,
actions,
mutations,
};
这是我的组件:
<template>
{{ seats }}
</template>
<script>
/* import API from '../api' */
import { mapGetters, mapActions } from 'vuex';
export default {
name: "Seats",
methods: {
...mapActions([
'streamSeats',
'setRoomInfo',
]),
},
computed: {
...mapGetters([
'seats',
'roomInfo',
'setSeats',
]),
},
watch: {
roomInfo: {
handler(newValue) {
if (newValue.userID && newValue.gameID) {
this.streamSeats();
}
},
deep: true,
},
},
components: {},
data: function() {
return {
alignment: 'center',
justify: 'center',
}
},
created() {
let gameID = this.$route.params.id
this.setRoomInfo({
gameID: gameID,
userID: this.$route.params.userID,
seatNumber: 1,
});
},
}
</script>
如您所见,我想在连接到 websocket 服务器后更改状态内席位的状态数据。
我花了很长时间试图解决这个问题,但没有运气。我尝试使用 mapstate、data 和其他一些技巧,但没有任何运气。我也在类似的 stackoverflow 线程中尝试了所有建议的解决方案。如果有人能给我一些关于如何通过这个障碍的提示,我将不胜感激。
【问题讨论】:
-
乍一看,您可能没有将
state传递到您的操作中,例如:async streamSeats({ commit, state }) -
我已将状态定义为存储文件中的全局变量。所以它应该在任何地方都可以访问。请注意,我遵循了本教程中的项目设置,看起来不错且模块化:youtube.com/…
-
啊,明白了。我也看到了“seatsd”吸气剂,但这可能只是一个错字。您是否收到任何错误消息?我认为 {{ seat }} 需要被包裹在一个非模板元素中。
标签: vue.js state vuex propagation