【问题标题】:How to update state in a component when the value changed at vuex store?当 vuex 商店的值发生变化时,如何更新组件中的状态?
【发布时间】:2018-03-07 15:14:16
【问题描述】:

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

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

在组件中,我从商店收到 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在store设置为false,变化并没有反映到组件中,所以通知框没有消失。

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

【问题讨论】:

    标签: vue.js vuejs2 vuex


    【解决方案1】:

    代码正在设置中

    store.showPromptMsg = false;
    

    我希望你想要

    state.showPromptMsg = false;
    

    【讨论】:

      【解决方案2】:

      在您的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;
          },
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-08-17
        • 2017-06-30
        • 2019-10-05
        • 2021-04-10
        • 2017-01-10
        • 2017-07-06
        • 2017-02-11
        • 2018-08-19
        相关资源
        最近更新 更多