Programing

Vuex 저장소 개체 반복

c10106 2022. 3. 9. 09:36
반응형

Vuex 저장소 개체 반복

나는 Vue.js와 Vuex를 처음 접하고 샘플 앱을 사용해 본다.이게 시나리오야

나는 지정된 이름을 키로 하여 객체에 알림을 저장하는 알림 저장 모듈을 가지고 있다.

{
  'message1': {
    type: 'info',
    message: 'This is an info message.',
    isShown: true,
  },
  'message2': {
    type: 'success',
    message: 'This is a success message.',
    isShown: true,
  },
  'message3': {
    type: 'error',
    message: 'This is an error message.',
    isShown: true,
  }
}

그리고 이건 제 Vuex 모듈인데,

const state = {
  notifications: {},
};

const mutations = {
  setNotification(state, { message, type, name }) {
    state.notifications[name] = {
      message,
      type,
      isShown: true,
    }
  },
  removeNotification(state, name) {
    delete state.notifications[name];
  }
};

const actions = {
  async showNotification(context, options) {
    await context.commit('setNotification', options);
  },
  async removeNotification(context, name) {
    await context.commit('removeNotification', name);
  }
}

const getters = {
  isNotificationShown: (state, getters) => {
    return getters.getNotificationMessageList.length > 0;
  },
  getNotificationMessageList: state => {
    return state.notifications;
  },
}

export default {
  state,
  actions,
  mutations,
  getters,
}

그리고 이건 내 구성요소야

<template>
  <div v-if="isShown">
    <div v-for="(notice, name, index) in notificationMessageList" :key="name">
      {{ index }} - {{ notice.type }} - {{ notice.message}}
    </div>
  </div>
</template>

<script>
export default {
  computed: {
    isShown() {
      return this.$store.getters.isNotificationShown;
    },
    notificationMessageList() {
      return this.$store.getters.getNotificationMessageList; 
    },
  },
};
</script>

Vue Development 툴에 확인해보니 스토어가 업데이트되고, 내가 스토어에 전달하고 있는 알림 메시지가 포함된 구성 요소도 업데이트된다.그러나 구성요소는 렌더링되지 않고 있다.하지만 같은 데이터를 컴포넌트에 하드코딩하여 사용하면 효과가 있다.

이것이 Vuex 스토어를 구성 요소에 연결하는 올바른 방법인지 잘 모르겠어.

부에 반응성 문제야Vue를 반응하게 만들려면 참조를 업데이트해야 한다.사용할 수 있다JSON.parse(JSON.stringify())또는 ES6 구문을 사용하십시오.

const mutations = {
  setNotification(state, { message, type, name }) {
    state.notifications = {
      ...state.notifications,
      [name]: {
        message,
        type,
        isShown: true
      }
    }
  },
  removeNotification(state, name) {
    const newNotifications = {...state.notifications}
    delete newNotifications[name]
    state.notifications = newNotifications
  }
};

참조URL: https://stackoverflow.com/questions/55037644/iterating-over-a-vuex-store-object

반응형