Automatic loading when the interface is called (global)

This function can be realized by displaying the loading before calling the interface and hiding the loading after the interface request ends.

For example, before calling the interface each time, a global loading component can be displayed to remind the user that the data is being loaded. After the interface request ends, hide the loading component.

The specific implementation method can first define a loading component in the global settings of the project, and display it before calling the interface, and then use the interceptor to monitor the status change of the interface request, and hide the loading component after the interface request succeeds or fails.

// 在项目全局定义loading组件

<template>
  <div class="loading" v-show="isLoading">
    <svg viewBox="0 0 32 32" width="32" height="32" fill="#333">
      <circle transform="translate(8 0)" cx="0" cy="16" r="0">
        <animate attributeName="r" values="0; 4; 0" dur="1.2s" repeatCount="indefinite"></animate>
        <animate attributeName="cx" values="0; 8; 16; 8; 0" dur="1.2s" repeatCount="indefinite"></animate>
      </circle>
      <circle transform="translate(16 0)" cx="0" cy="16" r="0">
        <animate attributeName="r" values="0; 4; 0" dur="1.2s" repeatCount="indefinite"></animate>
        <animate attributeName="cx" values="0; 8; 16; 8; 0" dur="1.2s" repeatCount="indefinite"></animate>
      </circle>
      <circle transform="translate(24 0)" cx="0" cy="16" r="0">
        <animate attributeName="r" values="0; 4; 0" dur="1.2s" repeatCount="indefinite"></animate>
        <animate attributeName="cx" values="0; 8; 16; 8; 0" dur="1.2s" repeatCount="indefinite"></animate>
      </circle>
    </svg>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isLoading: false
    }
  },
  methods: {
    showLoading() {
      this.isLoading = true
    },
    hideLoading() {
      this.isLoading = false
    }
  }
}
</script>

// 在拦截器中监听接口请求状态变化

import loading from './loading.vue'

// 请求拦截器
axios.interceptors.request.use((config) => {
  loading.methods.showLoading() // 显示loading组件
  return config
}, (error) => {
  loading.methods.hideLoading() // 隐藏loading组件
  return Promise.reject(error)
})

// 响应拦截器
axios.interceptors.response.use((response) => {
  loading.methods.hideLoading() // 隐藏loading组件
  return response
}, (error) => {
  loading.methods.hideLoading() // 隐藏loading组件
  return Promise.reject(error)
})

In this way, the loading component will be displayed before calling the interface every time to let the user know that the data is being loaded. After the interface request is completed, the loading component will be hidden so that the user can see the complete content. 

 

Guess you like

Origin blog.csdn.net/weixin_69811594/article/details/130551759