在组件外(.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>
相关推荐
小粉粉hhh14 分钟前
Node.js(五)——编写接口
前端·javascript·node.js
Helen_cai18 分钟前
OpenHarmony http 网络请求封装与全局拦截实战(API Version23 + 适配版)
网络·网络协议·http·华为·harmonyos
大意的百合41 分钟前
Electron 应用如何上架微软商店:从 MSIX 打包到商店提交
javascript·microsoft·electron
名字还没想好☜1 小时前
Go error 处理:errors.Is/As 与错误包装
开发语言·后端·golang·go·错误处理
红糖奶茶1 小时前
Python 中 while 循环计数异常的常见原因分析与正确搓搓
开发语言·python
Lucky_Turtle1 小时前
【论文写作】PDF图片不清晰,打印生成PDF空白大,PDF字体嵌入
开发语言·pdf·c#
csdndenglu1 小时前
Easy3D:一个轻量级、易用、高效的C++库,用于处理和渲染3D数据,无复杂要求时可替代VTK
开发语言·c++·图形渲染·3d渲染
byte轻骑兵1 小时前
【AVRCP】规范精讲[41]:AV/C指令帧解析,蓝牙遥控交互的底层语言
c语言·开发语言·人机交互·智能制造·avrcp
发光小北1 小时前
Bronze100系列plc Modbus及自由口通信案例
开发语言·php
snow@li2 小时前
Java:后端项目会有一个类似前端node_modules的目录吗 / jar包在本地仓库 ~/.m2/repository 中按版本共存
java·开发语言·前端