vue3+pina 使用过程中报" getActivePinia was called with no active Pinia. Did you forget to install pinia?"

场景#

我们需要为应用所有发送网络请求之前显示loading,网络请求结束后取消loading。

  1. app.vue中加载loading组件,并由下面的控制
  2. 使用pina来存储loading的状态
  3. 在axios发送网络请求前后修改loading的状态

示例代码#

<loading v-if="showLoading" />
<script setup>
  import useMainStore from "@/stores/modules/main.js";
  import { storeToRefs } from "pinia";
  
  const mainStore = useMainStore();
  const { showLoading } = storeToRefs(mainStore);
</script>
// stores/modules/main.js
import { defineStore } from "pinia";
const useMainStore = defineStore("main", {
  state() {
    return {
      showLoading: false,
    };
  },
});
export default useMainStore;
// 发送网络请求的工具函数
import axios from "axios";
import { BASE_URL, TIMEOUT } from "./config";
import useMainStore from "../../stores/modules/main";
const mainStore = useMainStore();

class HyRequest {
  constructor(baseURL, timeout) {
    this.instance = axios.create({
      baseURL,
      timeout,
    });
  }
  request(config) {
    return new Promise((resolve, reject) => {
      mainStore.showLoading = true;
      this.instance.request(config).then((res) => {
        mainStore.showLoading = false;
        resolve(res.data);
      });
    });
  }
  get(url, config) {
    return this.request({ url, method: "get", ...config });
  }
  post(url, config) {
    return this.request({ url, method: "post", ...config });
  }
}

export default new HyRequest(BASE_URL, TIMEOUT);

上面运行会报下面的错误:

解决办法#

在调用pinia的某个store时可以传递第一个参数来指定pinia的值,也就是他没有找到pinia的实例.

import useMainStore from "../../stores/modules/main";
import pinia from "../../stores";
const mainStore = useMainStore(pinia);
posted @   ^Mao^  阅读(388)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示
主题色彩