sourcecode

변수가 어레이인 경우 vuex에서 상태를 변경하는 방법

copyscript 2022. 7. 30. 18:18
반응형

변수가 어레이인 경우 vuex에서 상태를 변경하는 방법

저는 Vue를 막 배우기 시작했는데 스스로 답을 찾을 수가 없었어요.

데이터베이스에서 동적으로 로드되는 데이터를 포함하는 어레이가 여러 개 있습니다.내부 개체에는 로드 상태를 식별하는 isLoaded 속성이 있습니다.

문제는요.

개체 전체를 변환에 전달하지 않고 isLoaded 값을 변경하려면 어떻게 해야 합니까?

예를 들어 인덱스와 배열 이름만 전달합니다.

지금은 이렇게 하고 있어요.

    export default new Vuex.Store({
      state: {
        books: [
          {
            id: 1,
            title: 'Random',
            img: '',
            href: '/',
            isLoaded: false
          }
        ],
        games: [
          {
            id: 1,
            title: 'Random',
            img: '',
            href: '/',
            isLoaded: false
          }
        ]
      },
      getters: {
        books(state) {
          return state.books
        },
        games(state) {
          return state.games
        }
      },
      mutations: {
        updateLoadStatus(state, item) {
          item.isLoaded = true
        }
      }
    })

프리로더 클래스를 추가하려면 isLoaded 프로포트가 필요합니다.

<div :class="{loading: !book.isLoaded}">
  <img :src="book.img" :alt="book.title" @load="updateLoadStatus(book)">
</div>

어레이가 2개보다 훨씬 많으므로 각각에 대해 별도의 변환은 하고 싶지 않습니다.

변이를 정의하는 방법은 다음과 같습니다.

mutations: {
        updateLoadStatus(state, payload) {
          state[payload.key][payload.index].isLoaded = payload.value;
        }
   }

이렇게 부르면

this.$store.commit('updateLoadStatus', { key: 'books', index: 1, value:true}); // based on the object you pass as payload..the mutation will update the corresponding array item.

언급URL : https://stackoverflow.com/questions/64840369/how-to-change-state-in-vuex-if-my-variable-is-an-array

반응형