在组件外(.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>
相关推荐
xiaoxue..3 小时前
用 Node.js 手动搭建 HTTP 服务器:从零开始的 Web 开发之旅!
服务器·前端·http·node.js
Glommer3 小时前
AST 反混淆处理示例
javascript·爬虫
二川bro3 小时前
第44节:物理引擎进阶:Bullet.js集成与高级物理模拟
开发语言·javascript·ecmascript
中文Python3 小时前
小白中文Python-双色球LSTM模型出号程序
开发语言·人工智能·python·lstm·中文python·小白学python
越努力越幸运5083 小时前
JavaScript进阶篇垃圾回收、闭包、函数提升、剩余参数、展开运算符、对象解构
开发语言·javascript
czhc11400756633 小时前
C# 1116 流程控制 常量
开发语言·c#
程序员ys3 小时前
Vue的响应式系统是怎么实现的
前端·javascript·vue.js
aduzhe3 小时前
关于在嵌入式中打印float类型遇到的bug
前端·javascript·bug
程序定小飞4 小时前
基于springboot的汽车资讯网站开发与实现
java·开发语言·spring boot·后端·spring