vant的Loading加载动画组件的使用,通过接口拿数据时显示加载状态

  1. 在store.js中使用vuex全局控制loading显示与隐藏

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    LOADING: false
  },

  mutations: {
    showLoading(state) {
      state.LOADING = true
    },
    hideLoading(state) {
      state.LOADING = false
    }
  }
  1. 新建loading公共组件页面

<template>
  <div class="loading">
    <van-loading type="spinner" color="#1989fa" />
  </div>
</template>

<script>
  import Vue from 'vue';
  import {Loading} from 'vant';
  Vue.use(Loading);
  export default {
    name: 'LOADING',
    data() {
      return {}
    },
  }
</script>

<style lang="scss" scoped>
  .loading {
    position: fixed;
    z-index: 9999;
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
  }
</style>
  1. 在App.vue中,将loading组件挂载到工程根节点

挂载到App.vue中之后所有的接口请求都会加载loading组件

可以在需要的页面单独引用

<template>
  <div id="app">
    <Loading v-show="LOADING"></Loading>
    ......//其他代码
  </div>
</template>

<script>
  import {mapState} from 'vuex'
  import Loading from '@c/Loading.vue'
  export default {
  // ...解构,将store中的state进行映射。
  // 在template中可以直接使用,不需要通过this.$store.state一个个获取store中的state数据。
    computed: {
      ...mapState(['LOADING'])
    },
    name: 'App',
    components: {Loading}
  }
</script>
  1. 在请求拦截器和响应拦截器中配置

在封装好的axios中,利用axios的拦截器实现请求时提交store显示loading;

请求失败或者完成提交store隐藏loading。

import Vue from "vue";
import axios from 'axios';
import store from '../../store';

// 请求拦截器
axios.interceptors.request.use(function (config) {
  store.commit('showLoading')
  return config;
}, function (error) {
  store.commit('hideLoading')
  return Promise.reject(error);
});

//响应拦截器
axios.interceptors.response.use((response) => {
  store.commit('hideLoading')
  return response.data;
}, (error) => {
  store.commit('hideLoading')
  return Promise.reject(error);
});

//绑定到vue原型中
Vue.prototype.$http = axios;
  1. 如果在单个请求中使用

// 在请求时
this.$store.commit('showLoading')

//请求完成后  
this.$store.commit('hideLoading')

猜你喜欢

转载自blog.csdn.net/m0_61663332/article/details/128610258