部件之间共享全球小齿轮存储



我有两个vue组件,它们有自己的加载器,安装在两个已经渲染的DOM节点中:

A部分:

import { createApp } from 'vue'
import ComponentA from '@/Vue/ComponentA.vue';
import {createPinia} from 'pinia';
createApp(ComponentA).use(createPinia()).mount(document.querySelector('.c-component-a'));

B部分:

import { createApp } from 'vue'
import ComponentB from '@/Vue/ComponentB.vue';
import {createPinia} from 'pinia';
createApp(ComponentA).use(createPinia()).mount(document.querySelector('.c-component-b'));

现在,我想将一个全球小齿轮库加载到多个组件中:

Pinia商店:

import {defineStore} from 'pinia';
export type RootState = {
foobar: number;
}
export const useGlobalApplicationStore = defineStore({
id: 'global',
state: () => ({
foobar: 100
} as RootState),
actions: {
setFoobar(payload: number): void {
this.foobar = payload;
}
},
getters: {
getFoobar(state: RootState): number {
return state.foobar;
}
}
})

如果组件A在此存储中设置了一个值,那么组件B应该对更改做出反应。

A部分:

const globalApplicationStore = useGlobalApplicationStore();
setTimeout(() => {
globalApplicationStore.setFoobar(400);
}, 2000);

如预期的那样,组件A中{{globalApplicationStore.foobar}}的输出在2秒钟后从100变为400。

B部分:

const globalApplicationStore = useGlobalApplicationStore();

组件B中{{globalApplicationStore.foobar}}的输出不会从100更改为400。我想,这两个组件都将存储作为本地实例加载。

如何在单独安装的组件之间共享存储?

经过长时间的搜索,我发现这很容易(通常…(。在我的例子中,我使用Vue.js的渐进特性将应用程序放在HTML代码的不同位置。具体来说,我想在布局的标题中填充一个购物车图标,其中包含项目数量。所以我用App.vue作为我的产品应用程序,用Basket.vue作为篮子指示器。

简单的技巧是实例化pinia一次。假设您有一个main.js作为应用程序的入口点:

import { createApp } from "vue";
import App from "./App.vue";
import Basket from "./Basket.vue";
import {createPinia} from 'pinia';
const pinia = createPinia();
// Init App
createApp(App)
.use(pinia)  
.mount("#app");
// Init Basket
createApp(Basket)
.use(pinia)   
.mount("#basket");

在你的App.vue中,你只需要导入你的商店(在我的例子中是一个产品商店和一个购物车商店(。

<script setup>
... import components ...
import {useProductStore} from "@/stores/ProductStore";
import {useCartStore} from "@/stores/CartStore";
const productStore = useProductStore();
const cartStore = useCartStore();
productStore.fill();
</script>
<template>
... your components ...
</template>

在你的篮子里也是一样的.ve:

<script setup>
import CartWidget from "@/components/CartWidget.vue";
import {useCartStore} from "@/stores/CartStore";
import {useProductStore} from "@/stores/ProductStore";
const cartStore = useCartStore();
const productStore = useProductStore();
productStore.fill();
</script>
<template>
<div class="container">
<CartWidget/>
</div>
</template>

就是这样。

"pinia":"2.0.17";,"vue":"3.2.39";

相关内容

最新更新