天天看點

vue element admin中發送請求和設定loading效果

需求:在表格資料加載完成前進入loading顯示資料正在加載,資料加載完成後取消loading效果,axios的逾時處理和異常的處理之後進行取消loading效果。

小編接下來就根據這個這個需求進行分析:

1)首先是配置axios,在main.js當中進行引入axios

import axios from 'axios'

這裡是手動導入的axios 沒有用架構自帶的。

然後再main.js當中注冊自己的axios

Vue.prototype.$axios = axios

接下來就可以在自己的vue檔案裡面使用$axios進行發送請求了使用axios發送get請求和post請求請見:

2)設定axios的逾時,在main.js裡面進行設定axios.defaults.timeout = 6000; 這裡設定的是6秒,然後進行添加request和response的攔截器

在mian.js當中進行如下的設定

// 添加request攔截器
axios.interceptors.request.use(function (config) {
  // Do something before request is sent
  return config;
}, function (error) {
  // Do something with request error
  return Promise.reject(error);
});

// 添加response的攔截器
axios.interceptors.response.use(function (response) {
  // Do something with response data
  return response;
}, function (error) {
  // Do something with response error
  return Promise.reject(error);
});
           

設定以後便可以在請求的catch(error=> {doSomthing})裡面進行相應的操作可以進行重新發送請求或者清除loading的動畫效果

3)loading動畫的設定

在自己的vue檔案當中進行設定在我這裡是在table當中進行的設定也就是在template當中進行添加屬性el-table-column中進行的設定 在template當中進行添加屬性v-loading

然後再在data中進行設定

loading: this.$loading({
        lock: true,
        text: "資料加載中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      })
           

之後再axios發送請求擷取到資料之後進行添加 this.loading.close();

最後當資料請求異常的時候釋放loading

this.$axios.get().then(
	res=>{
		doSomthing
		this.loading.close()	
		}).catch(error=>{
			doSomthing
			this.loading.close()
	})
           

這樣既可在資料請求的時候進入loading頁面,資料請求成功釋放loading,資料請求失敗做出相應的處理并釋放loading

需要注意的是當再次進行資料請求的時候需要進行設定loading=true。

這次的分享就到這裡,如果有什麼疑問歡迎提問。