在组件外(.js文件)中使用pinia的方法2--在http.js中使用pinia

解决方案一

说明:评论反馈有点问题,测试后发现不能存动态值,并且会影响数据持久化插件(如pinia-plugin-persistedstate)
解决方案二

现在给出解决方案二:在http.js中使用pinia

步骤如下:
1、在stores中创建loading.js

javascript 复制代码
import { defineStore } from "pinia";
export const useLoadingStore = defineStore("loading", {
  state: () => ({
    isLoading: false,
    requestCount: 0,
  }),

  actions: {
    showLoading() {
      this.requestCount++;
      this.isLoading = true;
    },

    hideLoading() {
      this.requestCount--;
      if (this.requestCount <= 0) {
        this.requestCount = 0;
        this.isLoading = false;
      }
    },

    resetLoading() {
      this.requestCount = 0;
      this.isLoading = false;
    },
  },

  getters: {
    getLoadingState: (state) => state.isLoading,
  },
});

2、在http.js中引入

(1)、引入

javascript 复制代码
import { useLoadingStore } from "@/stores/loading";

let loadingStore;

// 初始化loadingStore(需要在Vue应用上下文可用后调用)
export const initHttp = (app) => {
  loadingStore = useLoadingStore(app);
};

(2)、请求拦截时,显示loading

javascript 复制代码
if (loadingStore) {
  loadingStore.showLoading();
}

(3)、响应拦截时,隐藏loading

javascript 复制代码
if (loadingStore) {
  loadingStore.hideLoading();
}

3、在main.js中引入

javascript 复制代码
 import { initHttp } from "@/utils/http";

  app.use(pinia)
 // 初始化 http,传入 pinia 实例
 // 注意顺序,在use后,mount前
  initHttp()

app.mount('#app')

4、在App.vue中使用

javascript 复制代码
<template>
  <div id="app">
    <RouterView />
    <GlobalLoading  v-if="isLoading" />
  </div>
</template>

<script setup>
import { onMounted } from 'vue'
import { useLoadingStore } from '@/stores/loading'
// 自定义的loading组件
import GlobalLoading from '自定义的loading组件'


const loadingStore = useLoadingStore();
const isLoading = computed(() => loadingStore.isLoading);

onMounted(() => {
  // 确保应用启动时loading状态正确
  loadingStore.resetLoading()
})
</script>
相关推荐
竹林81812 小时前
Web3表单签名验证:我用 wagmi 和 ethers 给 DApp 加了一个“免密登录”,踩坑记录全在这了
javascript
用户69903048487512 小时前
try catch使用场景 处理同步代码错误兼容用的
javascript·uni-app
LDR00612 小时前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
雪碧聊技术12 小时前
Tree.js是什么?一文讲透
开发语言·javascript·ecmascript
码云数智-园园12 小时前
C++20 Modules 模块详解
java·开发语言·spring
VidDown13 小时前
VidDown 工具站:免费、本地优先的开发者工具箱
javascript·编辑器·音视频·视频编解码·视频
swordbob13 小时前
NIO的channel中什么是 fd(File Descriptor,文件描述符)
java·开发语言·nio
源分享13 小时前
Java线程同步的多种实现方法(非常详细)
java·开发语言·jvm
Luminous.14 小时前
C语言--day30
c语言·开发语言
何以解忧,唯有..14 小时前
Go语言循环语句详解:for、range与循环控制
开发语言·算法·golang