前言
不知道大家有沒有遇到過這樣一種情況? vuex中的state會(huì)在某一個(gè)組建中使用,而這個(gè)狀態(tài)的初始化是通過異步加載完成的。組件在渲染過程中,獲取的state狀態(tài)為空。也就是說組件在異步完成之前就已經(jīng)完成渲染了,導(dǎo)致組件的數(shù)據(jù)沒有來得及渲染。
問題舉例
舉例說明如下:
// topo.vuecreated() { this.getUserAndSysIcons();},methods: { getUserAndSysIcons() { const self = this; // 用戶圖標(biāo) iconApi.getUserIcons().then(response => { self.$store.dispatch('setUserIcons', response.data); }); }}在topo.vue中created或者mounted完成的時(shí)候調(diào)用 getUserAndSysIcons() 異步初始化userIcons,方便在其他組件中使用這個(gè)數(shù)據(jù)。
// modifyhost.vuemounted() { this.userIcons = this.$store.state.topo.userIcons; // 用戶圖標(biāo)}在modifyhost.vue中渲染數(shù)據(jù)是,需要使用userIcons。在modifyhost.vue組件mounted完成的時(shí)候,userIcons數(shù)據(jù)還沒有被初始化。導(dǎo)致modifyhost.vue渲染為空。

思考
想的是,當(dāng)topo.vue中異步獲取userIcons完成的時(shí)候,再去將modifyhost.vue組件中的userIcons初始化。這樣就會(huì)自動(dòng)改變完成渲染。那么怎么知道異步什么時(shí)候完成呢?
于是就想到了vue一個(gè)好東西watch監(jiān)聽,監(jiān)聽某一個(gè)數(shù)據(jù)的變化。我們都知道是,很容易監(jiān)聽組件中局部數(shù)據(jù)的變化。那么,這里怎么去監(jiān)聽state中的變化呢?于是有利用了computed計(jì)算屬性。具體操作如下:
解決
在computed中寫一個(gè)計(jì)算屬性getUserIcons,返回狀態(tài)管理中的userIcons。然后在watch中監(jiān)聽這個(gè)計(jì)算屬性的變化,對(duì)modifyhost.vue中的userIcons重新賦值。
computed: { getUserIcons() { return this.$store.state.topo.userIcons; }},watch: { getUserIcons(val) { this.userIcons = val; }}最終效果

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注