有什么办法可以在Pinia中可以拿到vue的实例吗?
环境 vite + vue3 + vuerouter + Pinia
vite版本:2.9.0 vue版本:3.2.25 vuerouter 版本:4.0.14 pinia版本:2.0.13
需求
我在vue的实例上绑定了一个全局的socket 在所有页面都可以使用 所有的请求都是通过websocket 整个应用就一个socket单例 所有的网络请求我都要通过这个socket发送
现在有个需求是需要去做权限校验
我需要根据我所登入的嵌入式设备获取对应的设备能力去动态的渲染tab栏 及 一个设置页面的侧边栏
import {getCurrentInstance} from "vue";
// 通过getCurrentInstance获取vue的实例
const { $socket: socket } =
getCurrentInstance().appContext.config.globalProperties;
想法
在挂载的时候 去获取当前的vue实例
createApp(App)
.use(socketPlugin, {
url: getHost(),
})
.use(router)
.use(createPinia())// 这一步我在store中 请求后台数据 进行筛选需要展示在页面的上的tab
.mount("#app");
我想象的实现
// store/userInfo.js
import { defineStore } from "pinia";
import { getCurrentInstance } from "vue";
console.log(getCurrentInstance());// undefined
export const useInfoStore = defineStore("userInfo", {
state: () => ({
userName: "",
password: "",
}),
getter() {
doubleCount: (state) => {
// do something
return getCurrentInstance()// 请求后台数据 过滤
}
}
actions: {
setUserinfo(palyload) {
// do something
// 挂载后 异步获取当前的vue实例
// console.log(getCurrentInstance());// undefined
},
},
});
整个 vue3 composition API + Pinia 就是希望你不要动不动就把什么东西绑在 vue 根实例上,所以首先你应该从根上改变这种做法:
你的全局 socket 实例应该仅使用 js module 管理,独立存在。