pinia如何在组件外使用并修改 store?

发布时间 2023-04-03 15:23:50作者: 蓓蕾心晴

问题

在 vue3 + pinia 开发中,使用了自定义指令  directives,指令实现在独立的 js 文件中,想通过监听 dom 元素的变化修改 pinia 的 state 状态,直接在初始化调用 store 函数,

directives/index.js

import { useLayerStore } from "@/stores/";
const layer = useLayerStore();

会报错:

Uncaught Error: [?]: getActivePinia was called with no active Pinia. Did you forget to install pinia?
    const pinia = createPinia()
    app.use(pinia)
This will fail in production.
    at useStore (pinia.mjs:1696:19)
    at index.js:8:1

原因为此时全局 pinia还没有注册成功导致;

解决

初始化调用 store函数放在 mounted钩子中调用,即可正常使用:

const drag = {
    mounted(el, binding) {
        const layer = useLayerStore();
        }
}

// 挂载,注册
const directives = {
    install: function (app) {
        app.directive("drag", drag);
    },
};
export default directives;

 参见官方文档