インターフェイス経由でデータを取得するときに読み込みステータスを表示するための vant の読み込みアニメーション コンポーネントの使用

  1. vuex を使用して、store.js での読み込み表示と非表示をグローバルに制御する

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. 新しいロード用パブリックコンポーネントページを作成する

<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 で、読み込みコンポーネントをプロジェクトのルート ノードにマウントします。

App.vue にマウントされた後、すべてのインターフェイス要求は読み込みコンポーネントを読み込みます。

必要なページにて別途お見積り可能です

<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 インターセプターを使用して、リクエスト時にストア表示のロードを送信します。

リクエストが失敗するか、送信が完了すると、ストアは読み込みを非表示にします。

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
おすすめ