在進入一個頁面的時候,一般在獲取數據的同時,會先顯示一個 loading ,等請求結束再隱藏 loading 渲染頁面,只需要用一個屬性去記錄請求的狀態,再根據這個狀態去渲染頁面就好了
async handler() { this.loading = true await fetch() this.loading = false}
雖然是很簡單的功能,可是要處理的地方多的時候,還是很繁瑣的,就想著能不能統一設置處理請求的 loading ,然后頁面根據 loading 的狀態決定要顯示的內容,就根據自己的想法做了一些封裝,自動給所有 ajax 請求設置 loading 狀態,主要思路是把所有請求集中到單一實例上,通過 proxy 代理屬性訪問,把 loading 狀態提交到 store 的 state 中
安裝
$ npm install vue-ajax-loading
演示
使用
配置 store 的 state 及 mutations
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
去訪問請求狀態,如:
<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() } }}
Options
store
Vuex.Store 創建的實例
service
包含所有請求的對象,可以配置 global 和 modules 屬性
總結
以上所述是小編給大家介紹的為vue項目自動設置請求狀態的配置方法,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!
新聞熱點
疑難解答