首页 > 解决方案 > 如何检查是否加载了 JSON 数据

问题描述

我使用 axios 在 vuex 中获取我的 JSON 文件,以便在多个组件上使用获取的数据。问题是我的页面在所有数据加载之前呈现。以下内容有效,因为我将渲染延迟了 2 秒,如果没有此超时,则会导致错误。我想以正确的方式做到这一点,但不知道该怎么做。

商店.JS

Vue.use(Vuex);    
const store = new Vuex.Store({
    state: {
        poss: null
    },
    getters: {
        NAME: state => {
            return state.name
        },
        POSS: state => {
            return state.poss
        }
    },
    mutations: {
        SET_POSS : (state,payload) => {
          state.poss = payload
        },
        ADD_POSS : (state,payload) => {
          state.poss.push(payload)
        },
      },
      actions:{
       GET_POSS : async (context,payload) => {
          let { data } = await axios.get("json/poss.json")
          context.commit('SET_POSS',data)
       },
       SAVE_POSS : async (context,payload) => {
          let { data } = await axios.post("json/poss.json")
          context.commit('ADD_POSS',payload)
       }
    }
});

组件.VUE

module.exports = {          
        mounted:function(){
            var self = this;
            setTimeout(function () {
                self.mkPageload()
            }, 2000);
       },
       methods: {
            mkPageload: function(){ 
                let positions = this.$store.getters.POSS.pos            
                Object.keys(positions).forEach(key => { 
                   // rendering
                }
            }
       }
}

期望的结果是页面仅在 JSON 文件中的所有数据都已加载后才呈现。

标签: vue.jsaxios

解决方案


有几种方法可以解决这个问题。

  • 您可以在组件中使用等待/异步。

    async mounted () {
       await userStore.getAll()
       // access getter and render
    },
    
  • 您可以观看 vuex 变量(可以在没有异步的情况下完成,但我喜欢添加它们)

    async mounted () {
       await userStore.getAll()
    },
    computed: {
    ...mapGetters('users')
    }, 
    watch: {
        users(newValue, oldValue) {
           ....
           // render
        }
    }
    

不要忘记导入 mapGetters:https ://vuex.vuejs.org/guide/getters.html


推荐阅读