vue3+pina 使用过程中报" getActivePinia was called with no active Pinia. Did you forget to install pinia?"
场景
我们需要为应用所有发送网络请求之前显示loading,网络请求结束后取消loading。
- app.vue中加载loading组件,并由下面的控制
- 使用pina来存储loading的状态
- 在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);