Theory: Axios Calls (Specifically for VueJS)

泪湿孤枕 提交于 2021-02-05 08:33:34

问题


On component mount(), Axios fetches information from the back end. On a production site, where the user is going back and forth between routes it would be inefficient to make the same call again and again when the data is already in state.

How do the pros design their VueJS apps so that unnecessary Axios calls are not made?

Thank you,


回答1:


If the data is central to your application and being stored in Vuex (assuming that's what you mean by "state"), why not just load it where you initialise your store?

// store.js
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'wherever'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    centralData: {}
  },
  mutations: {
    setCentralData (state, centralData) {
      state.centralData = centralData
    }
  },
  actions: {
    async loadCentralData ({ commit }) {
      const { data } = await axios.get('/backend')
      commit('setCentralData', data)
    }
  }
}

// initialise
export const init = store.dispatch('loadCentralData')

export default store

If you need to wait for the dispatch to complete before (for example) mounting your root Vue instance, you can use the init promise

import Vue from 'vue'
import router from 'path/to/router'
import store, { init } from 'path/to/store'

init.then(() => {
  new Vue({
    store,
    router,
    // etc
  }).$mount('#app')
})

You can import and use the init promise anywhere in order to wait for the data to load.



来源:https://stackoverflow.com/questions/62337294/theory-axios-calls-specifically-for-vuejs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!