在组件外(.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>
相关推荐
lly2024063 小时前
Bootstrap 警告框
开发语言
2601_949146533 小时前
C语言语音通知接口接入教程:如何使用C语言直接调用语音预警API
c语言·开发语言
曹牧3 小时前
Spring Boot:如何测试Java Controller中的POST请求?
java·开发语言
KYGALYX4 小时前
服务异步通信
开发语言·后端·微服务·ruby
zmzb01034 小时前
C++课后习题训练记录Day98
开发语言·c++
猫头虎4 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
Moment5 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
YUJIANYUE5 小时前
PHP纹路验证码
开发语言·php
爱敲代码的小鱼5 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax
仟濹5 小时前
【Java基础】多态 | 打卡day2
java·开发语言