loading.js 1.52 KB
/*
 * @Date: 2025-11-04 10:45:00
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2025-11-04 10:45:00
 * @FilePath: /src/stores/loading.js
 * @Description: 全局Loading状态管理
 */
import { defineStore } from 'pinia'

/**
 * 全局loading状态管理
 * @description 使用计数的方式管理并发请求的loading显示与隐藏
 */
export const useLoadingStore = defineStore('global_loading', {
    state: () => ({
        // 当前正在进行中的网络请求数量
        pending_count: 0,
        // 是否显示全屏loading
        is_loading: false
    }),

    getters: {
        // 是否存在进行中的请求
        has_pending(state) {
            return state.pending_count > 0
        }
    },

    actions: {
        /**
         * 开始一次请求,增加计数并显示loading
         * @returns {void}
         */
        start() {
            this.pending_count += 1
            this.is_loading = true
        },

        /**
         * 结束一次请求,减少计数,当计数归零时隐藏loading
         * @returns {void}
         */
        end() {
            if (this.pending_count > 0) {
                this.pending_count -= 1
            }
            if (this.pending_count === 0) {
                this.is_loading = false
            }
        },

        /**
         * 请求异常或需要强制关闭时,重置计数并隐藏loading
         * @returns {void}
         */
        reset() {
            this.pending_count = 0
            this.is_loading = false
        }
    }
})