如何在vuex存储中更改值时更新组件中的状态?

时间:2017-09-26 11:50:04

标签: vue.js vuejs2 vuex

在vuex商店中,我有这样的突变,它从一个组件接收消息,并在另一个组件上显示/隐藏提示消息(成功登录后像You are logged in提示):

setPromptMsg: function (state, msg) {
    state.showPromptMsg = true;
    state.promptMsg = msg;
        function sleep (time) {
        return new Promise((resolve) => setTimeout(resolve, time));
      }                           
     sleep(3000).then(() => {
          store.showPromptMsg = false;
          state.promptMsg = '';
          console.log('show message set to false');
      });
},

在compoenet中,我从商店收到showPromptMsg作为计算属性:

computed: {
    showPromptMsg () {
        return this.$store.state.showPromptMsg;
    },
    promptMsg () {
    return this.$store.state.promptMsg;
    }
}

模板中的显示/隐藏提示消息:

   <div v-show="showPromptMsg">
      <div class="text-center" >
         <strong> {{promptMsg}} </strong>
      </div>
  </div>

问题在于,当提示是超时时,即在商店中将showPromptMsg设置为false时,更改不会反映到组件中,因此通知框不会消失。

我想知道解决这个问题的惯用方法是什么?

2 个答案:

答案 0 :(得分:3)

代码正在设置

store.showPromptMsg = false;

我希望你想要

state.showPromptMsg = false;

答案 1 :(得分:1)

NotificationBarComponent.vue模板中:

<div>
    <div class="text-center" >
       <strong> {{ message }} </strong>
    </div>
</div>

在您的NotificationBarComponent.vue组件定义中添加一个prop以将自定义消息传递给显示,并在挂载时启动超时以隐藏通知:

export.default {
    props: ['message'],
    mounted() {
        window.setTimeout(() => {
            this.$store.commit('handleMessageState', false)
        }, 3000);
    }   
};
商店中的

创建一个属性来管理通知显示isNotificationBarDisplayed: false

handleMessageState(state, payload) {
    state.isNotificationBarDisplayed = payload;
}

您想要使用它的任何地方:

<notification-bar-component v-show="isNotificationBarDisplayed" message="Some message here"></notification-bar-component>

computed: {
    isNotificationBarDisplayed () {
        return this.$store.state.isNotificationBarDisplayed;
    },
}