当 vuex store 的值发生变化时,如何更新组件中的状态?

How to update state in a component when the value changed at vuex store?

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

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;
    }
}

模板中的show/hide提示信息:

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

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

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

代码正在设置

store.showPromptMsg = false;

我想你想要

state.showPromptMsg = false;

在您的 NotificationBarComponent.vue 模板中:

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

在您的 NotificationBarComponent.vue 组件定义中添加一个道具以传递自定义消息以显示并在安装时启动超时以隐藏通知:

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;
    },
}