【发布时间】: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