2017-05-04 105 views
1

我想激活/取消激活簡單微調框。Vuejs Vuex組件在商店更改時未更新

我已經創建存儲來處理旋轉的狀態:

const spinnerStore = { 
    state: { 
    isActive: false 
    }, 

    mutations: { 
    startSpinner: function (state) { 
     console.log('start'); 
     state.isActive = true 
    }, 

    stopSpinner: function (state) { 
     console.log('stop'); 
     state.isActive = false 
    } 
    }, 

    actions: { 
    startSpinner: function ({commit}) { 
     commit('startSpinner'); 
    }, 

    stopSpinner: function ({commit}) { 
     commit('stopSpinner'); 
    } 
    } 
} 

const store = new Vuex.Store({ 
    modules: { 
     'mapEditor': mapEditorStore, 
     'spinner': spinnerStore 
    } 
}); 

我創建Vue公司來處理視圖。

<script type="x-template" id="vueSpinnerTemplate"> 
    <div class="mdl-spinner mdl-js-spinner mdl-spinner--single-color" style="position: absolute; bottom: 50px; right: 50px; z-index: 10" v-bind:class="{'is-active': isActive}"> </div> 
</script> 

<script> 

var vm = new Vue({ 

    store, 

    template: '#vueSpinnerTemplate', 

    computed: { 
     isActive: function() { 
      console.log('called'); 
      return this.$store.state.spinner.isActive 
     } 
    } 
}).$mount('#spinner-mount-point'); 

</script> 

Vue.use(Vuex)某處叫,因爲我有這個消息時,我嘗試這條線: [vuex] already installed. Vue.use(Vuex) should be called only once. 如果我在店裏的默認值設置爲true我看到我的微調,因此HTML /模板沒問題。

在我的代碼,我使用jQuery做一個異步請求,我希望我的微調展現出來,所以我使用:

store.dispatch('startSpinner'); 
$.ajax({ 
    url : "myUrl", 
    success: function (data) { 
     store.dispatch('stopSpinner'); 
    } 
}); 

Unfortanutelly,我看不到微調顯示出來。 (我的要求需要2個secondes)

所以,我看着在控制檯中,我看到:

稱爲 開始 停止 稱爲

這意味着該組件沒有啓動之間調用isActive和停止。

如何解決

感謝

編輯:我的解決方案beggining。

我的ajax請求是synchrone。我認爲它阻止組件渲染或類似的東西...當我把async: true可以看到微調

+0

我沒有在代碼中的任何地方看到'Vue.use(Vuex)',並且你沒有創建一個Vuex存儲('new Vuex.Store') - 你只是創建一個共享狀態變量。 – PatrickSteele

+0

我沒有把所有的代碼發佈,看我的編輯:) – Epitouille

回答

0

我不是絕對相信,如果這是問題,但我會嘗試創建一個「isActive」的getter。 它通常會看起來像那麼:

return this.$store.getters.spinnerIsActive 

我實際上並不知道如何創造vuex恆定的作品所以也許也像這樣

return this.$store.getters.spinner.spinnerIsActive 

return this.$store.spinner.getters.spinnerIsActive 

吸氣劑看起來像這樣:

getters = { 
    spinnerIsActive: state => state.isActive 
} 

您還可以查看我是如何構建store in my project的。這並不是那麼複雜,它可能會有所幫助。順便說一句,它不可能解決您的問題,但請注意,通常delete不會觸發事件,因此需要在here中使用Vue.delete()。