2017-09-26 364 views
2

在vuex商店我有此突变,其从一个组件接收MSG和是显示/隐藏提示消息在另一部件(成功登录后赞You are logged in propmpt):如何在vuex store中更改值时更新组件中的状态?

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时,更改不会反映到组件中,因此通知框不会消失。

我想知道什么是地道的方式来解决这个问题?

回答

3

的代码设置

store.showPromptMsg = false; 

我希望你要

state.showPromptMsg = false; 
1

在你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; 
    }, 
} 
相关问题