【问题标题】:Iterating over a Vuex store object遍历 Vuex 存储对象
【发布时间】:2019-07-28 23:26:32
【问题描述】:

我是 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 开发工具,发现商店确实更新了,我传递给商店的通知消息的组件也更新了。但是该组件没有被渲染。但是如果我通过在组件中硬编码来使用相同的数据,它就可以工作。

我不确定这是否是将 Vuex 存储连接到组件的正确方法。

【问题讨论】:

  • 你能为此创建 jsfiddle 吗?

标签: vue.js vue-component vuex vuex-modules


【解决方案1】:

这是 Vue 反应性问题。您需要更新引用以使 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
  }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-03
    • 2019-04-24
    • 1970-01-01
    • 2021-06-18
    • 2020-07-07
    • 2013-10-19
    • 2020-06-21
    • 1970-01-01
    相关资源
    最近更新 更多