当前位置: 首页 > news >正文

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

解决方案一
说明:评论反馈有点问题,测试后发现不能存动态值,并且会影响数据持久化插件(如pinia-plugin-persistedstate)
解决方案二
现在给出解决方案二:在http.js中使用pinia
步骤如下:
1、在stores中创建loading.js

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)、引入

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

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

if (loadingStore) {loadingStore.showLoading();
}

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

if (loadingStore) {loadingStore.hideLoading();
}

3、在main.js中引入

 import { initHttp } from "@/utils/http";app.use(pinia)// 初始化 http,传入 pinia 实例// 注意顺序,在use后,mount前initHttp()app.mount('#app')

4、在App.vue中使用

<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>
http://www.dtcms.com/a/605667.html

相关文章:

  • 虚拟机磁盘空间不够了,不重启扩盘
  • easychallenge(攻防世界)
  • 3.JavaScript_数组方法
  • 50013_基于微信小程序的校园志愿者系统
  • 网络维护工作谷歌seo网络营销价格
  • esp32-s3-supermini使用arduio IDE进行mpu6050的数据读取
  • C++ 建造者模式:复杂对象的“定制化分步构建”指南
  • 【开题答辩全过程】以 基于 Spring Boot的一品清餐外卖点餐系统的设计与实现为例,包含答辩的问题和答案
  • 【SpringBoot】36 核心功能 - 高级特性- Spring Boot 中的外部配置文件详解
  • 移动手机号码网站企业在网站建设上的不足
  • 深入解析Go语言GMP调度模型:高并发背后的核心机制
  • 怎么建立自己网站 asp高等学校处网站建设总结
  • 网站怎么做排查修复ppt免费下载模板网站
  • JAVA应用SCA安全扫描开源解决方案
  • 【Java Web学习 | 第十篇】JavaScript(4) 对象
  • 网站建设策划完整方案小程序是什么时候出来的
  • 解决SSL证书安装后网站仍显示“不安全”的问题
  • (已解决)vscode打开stm32cubemx生成的工程报红色波浪线警告
  • 做营销型网站用什么技术百度手机怎么刷排名多少钱
  • 信息安全的容灾与业务持续安全管理的措施
  • 毕业设计网站做几个页面古风淡雅ppt模板免费
  • Android AB升级(三) - update engine架构概述
  • 二叉树递归题目(一)
  • 太仓有没有做网站建设的专业网页设计价格
  • 工作手机监管系统:敏感词预警+行为监控,让销售更规范
  • 实战|SpringBoot+Vue3 医院智能预约挂号系统(含 AI 助手)
  • 网站分析报告范文动态asp.net网站开发
  • 南充做网站公司网站需要网监备案
  • 如何轻松安全地擦除手机数据以便以旧换新
  • 大模型强化学习-DPO