vue自定義全局loading組件

loading.vue 

<template>
  <div class="sync-loding" v-show="getLoading">
    <div class="ldbox">
      <span class="loading"></span>
      <span class="text">加載中...</span>
    </div>
  </div>
</template>

<script>
  import {mapGetters, mapActions} from 'vuex'

  export default {
    data() {
      return {}
    },
    computed: {
      ...mapGetters({
        getLoading: 'getLoading'
      })
    }
  }
</script>

<style lang="less" rel="stylesheet/less">
  .sync-loding, .loding {
    width: 16rem;
    height: 100%;
    position: fixed;
    z-index: 9999;
    left: 50%;
    top: 0;
    margin-left: -8rem;
    -webkit-overflow-scrolling: none;
    pointer-events: auto;
    -webkit-user-select: none;
    -webkit-user-drag: none;
    .loading {
      display: block;
      width: .8rem;
      height: .8rem;
      border: 3px solid #fff;
      top: 50%;
      left: 50%;
      margin-left: -.4rem;
      margin-top: -.6rem;
      position: absolute;
      border-radius: 50%;
      border-top-color: transparent;
      animation: rotate .5s linear infinite;
    }
    .text {
      position: absolute;
      bottom: 6px;
      width: 100%;
      text-align: center;
      font-size: .6rem;
    }
    .ldbox {
      font-size: .5rem;
      width: 3rem;
      height: 3rem;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      color: #fff;
      background: rgba(0, 0, 0, 0.39);
      border-radius: 5px;
    }
  }
</style>

在vuex中定義一個modules爲loading.js

import {SHOW_LOADING,HIDE_LOADING} from '../types'

const state = {
  status: false
}

const mutations = {
  [SHOW_LOADING](state){
    state.status=true
  },
  [HIDE_LOADING](state){
    state.status=false
  }
}

export default {
  state,
  mutations
}

定義type.js

export const SHOW_LOADING = 'SHOW_LOADING' //顯示loading
export const HIDE_LOADING = 'HIDE_LOADING' //隱藏loading

定義action.js

export const showLoading = ({ commit }) => {
  commit(types.SHOW_LOADING);
};

export const hideLoading = ({ commit }) => {
  commit(types.HIDE_LOADING);
};

定義store的index.js

import Vue from 'vue'
import Vuex from 'vuex'
import * as getters from './getters'
import * as actions from './actions'

Vue.use(Vuex);

import loading from './modules/loading'

export default new Vuex.Store({
  getters,
  actions,
  modules:{
    loading,
  }
})

接下來就可以使用store.dispatch('showLoading')和store.dispatch('hideLoading')來出發換個關閉loading組件

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章