programing

Vuex 상태 변경 내용이 Vue 구성 요소 템플릿에 전파되지 않음

javaba 2022. 8. 3. 22:31
반응형

Vuex 상태 변경 내용이 Vue 구성 요소 템플릿에 전파되지 않음

방금 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>

보시는 바와 같이 웹 소켓 서버에 접속한 후 내부 시트의 상태 데이터를 변경하고 싶습니다.

난 오랫동안 이걸 알아내려고 노력했지만 운이 없었어.나는 지도 상태, 데이터, 그리고 다른 몇 가지 속임수를 써보려고 했지만 아무런 운이 없었다.비슷한 스택오버플로우 스레드에서도 제안된 솔루션을 모두 사용해 보았습니다.누가 이 장애물을 어떻게 통과해야 하는지 힌트를 주시면 감사하겠습니다.

getters와 call map Getters를 정의할 때 몇 가지 불일치가 있습니다.

가게

const getters = {
  seatsd: state => state.seats,   // there is a typo in seats, you declared seatsd
  roomInfo: state => state.roomInfo,
};

요소

computed: {
  ...mapGetters([
    'seats',
    'roomInfo',
    'setSeats',  // this is not getters, this is mutations
  ]),
},

봐주셔서 감사합니다.오늘 Vuejs 크롬 확장을 설치했습니다.Chrome 개발 콘솔에 오류가 표시되는 방식을 변경했다고 합니다.다른 곳에서 발견되지 않은 오류가 몇 개 있어서 코드가 이 부분을 제대로 통과하지 못했습니다.이러한 문제를 해결한 후 컴포넌트의 데이터를 확인할 수 있었습니다.

언급URL : https://stackoverflow.com/questions/62014705/vuex-state-changes-are-not-propagated-to-vue-component-template

반응형