2017-06-02 24 views
1

我在理解以下煩惱:VueJS - 訪問存儲數據的內部安裝

我有一個store其中包含應用程序所需的變量。尤其是有globalCompanies哪些商店:

globalCompanies: { 
    current: [], 
    all: [], 
    currentName: "", 
} 

內的另一個組成部分,我要做到以下幾點:

mounted() { 
    this.$store.dispatch("fetchUsers"); 

    var currentName = this.$store.state.globalCompanies.currentName; 

    console.log(currentName); 
}, 

然而,這只是顯示爲空。我知道價值在那裏,因爲我有computed,它返回currentName,它在視圖本身內工作正常。它只是不喜歡它在安裝的組件中。

我在哪裏出錯了,我能做些什麼來解決這個問題?我真的需要捕捉公司名稱以便用於某些實時事件。

+0

是'state.globalCompanies.currentName'這個異步調用「fetchUsers」設置? – wostex

+0

@wostex不,它是由加載頁面時發生的另一個異步調用設置的。它在不同的組件 – Phorce

+0

嘗試檢索計算屬性中的'currentName',正如你所說的在那裏工作並在'mounted()'鉤子中使用該計算屬性 –

回答

4

作爲我們討論的結果是:

在這個問題Vuex狀態值,在組件的mounted掛鉤訪問,返回空值,因爲它是一個異步動作不前mounted執行解決設置。

當您需要在Vuex中的異步操作使用值進行解析時觸發某個函數時,您可以在計算屬性上使用watch來實現它,該屬性從Vuex狀態返回一個值。當在商店的變化值,計算出的屬性反映這些變化,並watch聽者執行:

const store = new Vuex.Store({ 
 
    state: { 
 
    globalCompanies: { 
 
     test: null 
 
    } 
 
    }, 
 
    mutations: { 
 
    setMe: (state, payload) => { 
 
     state.globalCompanies.test = payload 
 
    } 
 
    }, 
 
    actions: { 
 
    pretendFetch: ({commit}) => { 
 
     setTimeout(() => { 
 
     commit('setMe', 'My text is here!') 
 
     }, 300) 
 
    } 
 
    } 
 
}) 
 

 
new Vue({ 
 
    el: '#app', 
 
    store, 
 
    computed: { 
 
    cp: function() { // computed property will be updated when async call resolves 
 
     return this.$store.state.globalCompanies.test; 
 
    } 
 
    }, 
 
    watch: { // watch changes here 
 
    cp: function(newValue, oldValue) { 
 
     // apply your logic here, e.g. invoke your listener function 
 
     console.log('was: ', oldValue, ' now: ', newValue) 
 
    } 
 
    }, 
 
    mounted() { 
 
    this.$store.dispatch('pretendFetch'); 
 
    // console.log(this.cp, this.$store.state.globalCompanies.test); // null 
 
    // var cn = this.$store.state.globalCompanies.test; // null 
 
    // console.log(cn) // null 
 
    } 
 
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.js"></script> 
 
<script src="https://unpkg.com/[email protected]"></script> 
 
<div id="app"> 
 
    {{ cp }} 
 
</div>