如何编写全球商店插件?

发布于 2025-01-26 22:31:43 字数 597 浏览 2 评论 0原文

我正在尝试通过插件全球可用的反应性$ store对象,但无法使其正常工作。

store.ts

import {reactive} from "vue";

export default {
    install: (app:any, options:any) => {

        app.config.globalProperties.$store = reactive({})
    }
}

main.ts

import {createApp} from 'vue';
import app from "@/vue/app.vue";
import store from "@/scripts/store";

createApp(app)
    .use(store)
    .mount("#app");

现在我希望该插件在所有组件中可用,但是$ store保持未宣布的变量,当我尝试在组件内的< scipt设置中使用它时。

I'm trying to make a reactive $store object globally available via plugin but am failing to make it work.

store.ts:

import {reactive} from "vue";

export default {
    install: (app:any, options:any) => {

        app.config.globalProperties.$store = reactive({})
    }
}

main.ts:

import {createApp} from 'vue';
import app from "@/vue/app.vue";
import store from "@/scripts/store";

createApp(app)
    .use(store)
    .mount("#app");

Now I would expect for the plugin to be usable in all components, but $store stays an undeclared variable, when I try to use it in the <script setup> tag inside a component.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

白首有我共你 2025-02-02 22:31:43

虽然集中国家而不是将其分布在组件之间并不是一个坏主意,但具有全球参考的高度不佳。

取而代之的是,全局参考,创建事件总线或一长串发射链,此框架中的经典选项是通量模式。目前,VUE中最简单的通量实现和正式建议的是 pinia 。它以非常简单的方式完全满足您的要求。它具有非常好的打字稿支持,您只需要进口所需的商店,它们将在整个应用程序中反应地维护状态。

While it's not a bad idea to centralize the state instead of having it distributed among components, it is highly inadvisable to have global references.

Instead global reference, creating event buses or a long chain of emits, the classic option in this framework is the Flux pattern. Currently the simplest implementation of Flux in Vue and the one officially recommended is Pinia. It exactly meets your requirement in a very simple way. It has very good typescript support and you just have to import the stores you need where you need them and they will reactively maintain state throughout the app.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文