在進入一個頁面的時候,通常在獲取數據的同時,會先顯示一個 loading
,等請求結束再隱藏 loading
渲染頁面,只須要用一個屬性去記錄請求的狀態,再根據這個狀態去渲染頁面就行了html
async handler() {
this.loading = true
await fetch()
this.loading = false
}
複製代碼
雖然是很簡單的功能,但是要處理的地方多的時候,仍是很繁瑣的,就想着能不能統一設置處理請求的 loading
,而後頁面根據 loading
的狀態決定要顯示的內容,就根據本身的想法作了一些封裝,自動給全部 ajax
請求設置 loading
狀態,主要思路是把全部請求集中到單一實例上,經過 proxy
代理屬性訪問,把 loading
狀態提交到 store
的 state
中vue
$ npm install vue-ajax-loading
複製代碼
在線demo(打開較慢)node
import { loadingState, loadingMutations } from 'vue-ajax-loading'
const store = new Vuex.Store({
state: {
...loadingState
},
mutations: {
...loadingMutations
}
})
複製代碼
import { ajaxLoading } from 'vue-ajax-loading'
import axios from 'axios'
import store from '../store' // Vuex.Store 建立的實例
axios.defaults.baseURL = 'https://cnodejs.org/api/v1'
// 把請求集中到單一對象上,如:
const service = {
global: {
// 全局的請求
getTopics() {
return axios.get('/topics')
},
getTopicById(id = '5433d5e4e737cbe96dcef312') {
return axios.get(`/topic/${id}`)
}
},
modules: {
// 有命名空間的請求,命名空間就是 topic
topic: {
getTopics() {
return axios.get('/topics')
},
getTopicById(id = '5433d5e4e737cbe96dcef312') {
return axios.get(`/topic/${id}`)
}
}
}
}
export default ajaxLoading({
store,
service
})
複製代碼
完成以上配置以後,經過上面 export default
出來的對象去發送請求,就會自動設置請求的狀態,而後能夠在組件內經過 this.$store.state.loading
或 this.$loading
去訪問請求狀態,如:ios
<el-button type="primary" :loading="$loading.getTopics" @click="handler1">getTopics</el-button>
<el-button type="primary" :loading="$loading.delay" @click="delay">定時兩秒</el-button>
<el-button type="primary" :loading="$loading.topic.getTopics" @click="handler3">topic.getTopics</el-button>
複製代碼
import api from 'path/to/api'
export default {
methods: {
handler1() {
api.getTopics()
},
handler3() {
api.topic.getTopics()
},
delay() {
api.delay()
}
}
}
複製代碼
Vuex.Store 建立的實例git
包含全部請求的對象,能夠配置 global
和 modules
屬性github
掛載到 Vue.prototype
上的屬性名,默認是 $loading
ajax
github地址npm