理论:Axios 调用(专门针对 VueJS) [英] Theory: Axios Calls (Specifically for VueJS)

查看:21
本文介绍了理论:Axios 调用(专门针对 VueJS)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在组件 mount() 上,Axios 从后端获取信息.在生产站点上,用户在路由之间来回移动,当数据已经处于 state 时,一次又一次地进行相同的调用将是低效的.

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.

专业人士如何设计他们的 VueJS 应用程序,以免进行不必要的 Axios 调用?

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

谢谢,

推荐答案

如果数据是应用程序的核心并存储在 Vuex 中(假设这就是您所说的 状态"),为什么不只是在您初始化商店的地方加载它?

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

<小时>

如果您需要在(例如)挂载根 Vue 实例之前等待分派完成,您可以使用 init 承诺


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')
})

您可以在任何地方导入和使用 init 承诺以等待数据加载.

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

这篇关于理论:Axios 调用(专门针对 VueJS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆