鍍金池/ 問答/HTML/ vue根組件mounted的時候異步請求得到全局參數用于字段翻譯,存入store

vue根組件mounted的時候異步請求得到全局參數用于字段翻譯,存入store,子組件刷新有時取不到數據

項目使用vue,一些字段需要翻譯,后臺給了一個接口,用于獲取字典。
我在根組件mounted的時候發(fā)請求,

new Vue({
    data:{},
    methods:{
        getDic(){
            axios.post(url)
            .then(res=>{
                this.$store.commit('saveDic',res)
            })
        }
    },
    mounted(){
        this.getDic();
    }
})

store是這樣的:

const store = {
    state:{
        dictionary:{}
    },
    mutation:{
        saveDic(state,dic){
            state.dictionay = dic;
        }
    }
}

然后在子組件取參數

export default {
  data() {},
  methods:{
    getParams(){
        let dic = this.$state.dictionary
        console.log(dic)
    }
  },
  mounted(){
      this.getParams();
  }
}

現在問題來了,如果從其他頁面進入這個頁面,getParams()是似乎總是可以取到參數,但是如果在當前頁面刷新,就有可能無法取到參數,這是dic還是{}。很顯然這是一個異步的問題。

想到一個比較穩(wěn)妥的解決方案,寫一個action,先判斷state里面的dictionary有沒有,如果沒有就去發(fā)個請求,返回promise,在then里面寫之后的邏輯。每次需要翻譯的時候就去dispatch這個action。

但是這個項目幾乎每個頁面都需要這個翻譯的參數,有沒有辦法只請求一次,不用每次都去使用這個action?

目前的解決方案是用延時

mounted(){
    setTimeout(() => {
     this.getParams();
   }, 1000);
  }

用了之后好像再沒遇到過參數獲取不到的問題了。但是這種做法并不嚴謹。有沒有更穩(wěn)妥的做法?

回答