在组件外(.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>
相关推荐
1001101_QIA3 分钟前
C++中不能复制只能移动的类型
开发语言·c++
炸土豆4 分钟前
防抖节流里的this传递
前端·javascript
tryxr7 分钟前
HashTable、HashMap、ConcurrentHashMap 之间的区别
java·开发语言·hash
serendipity_hky9 分钟前
【go语言 | 第5篇】channel——多个goroutine之间通信
开发语言·后端·golang
林希_Rachel_傻希希10 分钟前
手写Promise--教学版本
前端·javascript·面试
无事好时节12 分钟前
Linux 线程
java·开发语言·rpc
ETA814 分钟前
`console.log([1,2,3].map(parseInt))` 深入理解 JavaScript 中的高阶函数与类型机制
前端·javascript
源代码•宸26 分钟前
分布式缓存-GO(简历写法、常见面试题)
服务器·开发语言·经验分享·分布式·后端·缓存·golang
Java编程爱好者26 分钟前
JUnit 5 中的 @ClassTemplate 实战指南
javascript