在网络请求期间添加loading......

83 阅读1分钟

这样可以增加用户体验,定义一个loading组件,设置自己想要的样式 在stores/modules/main.js中添加一个isLoading状态

const useMainStore = defineStore('main',{
  state: () => ({
    token:'',
    startDate: startDate,
    endDate: endDate,
    isLoading:true
  }),
})

loading组件中设置,给主类设置v-if

<div class="loading" 
   v-if="mainStore.isLoading"
   @click="loadingClick"
   > 

用户点击可以取消加载

const mainStore = useMainStore()
const loadingClick = () => {
  mainStore.isLoading = false
}

在request.index中添加拦截器

    this.instance.interceptors.request.use(config => {
      mainStore.isLoading = true
      return config
    },err => {
      return err
    })

    this.instance.interceptors.response.use(res => {
      mainStore.isLoading = false
      return res
    },err => {
      mainStore.isLoading = false
      return err
    })
  }