Vuejs使用vant组件之loading组件

4,791 阅读1分钟

1.下载vant库

# Vue 2 项目,安装 Vant 2:
npm i vant -S

# Vue 3 项目,安装 Vant 3:
npm i vant@next -S

2.新建vLoading.vue文件

提示:本文UI组件使用的是按需引入,具体配置点击此处查看

<template>
    <div class="van-loading" v-show="loading">
        <Loading size="300px" type="spinner" vertical text-size="60px" color="#0094ff">加载中...</Loading>
    </div>
</template>

<script>
import {Loading} from 'vant';
    //使用vuex来控制loading的显示隐藏
import {mapState} from 'vuex';
export default {
name: "VantLoading",
      components:{
  Loading
      },
      computed:{
  ...mapState([
    'loading'
  ])
      }

}
</script>

</style>

3.在App.vue文件中使用

<template>
  <div id="app">
      <VantLoading></VantLoading>
   <div>
</template> 

<script>
import VantLoading from "./plugin/vantloading/VantLoading";
components: {
  //注册组件
  VantLoading
},
</script>

4.store文件夹index.js

state:{
    loading:false;  //默认不显示
}

mutations:{
    setLoading(state, flag) {
        //flag在外界传入参数改变动画状态
        state.loading = flag;
      }
}

5.在axios请求拦截器中控制vuex状态

利用vuex状态管理来控制动画的显示隐藏

//记录请求跟响应的次数是否相等,相等才可以关掉动画
let count = 0;
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  count++;
  
  //在发送请求之前显示动画
  store.commit('setLoading', true);  //van-loading
  
  
  return config;
}, function (error) {
  // 对请求错误的时候关掉动画
  store.commit('setLoading', false);
  return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  count--;
  if (count === 0) {
    store.commit('setLoading', false);
  }
  return response;
}, function (error) {
  // 对响应错误做点什么
  store.commit('setLoading', false);
  return Promise.reject(error);
});