2017-09-26 365 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; 
    }, 
} 
相關問題