我有两个带有自己的加载器的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。我猜,这两个组件都将存储作为本地实例加载。
如何在单独安装的组件之间共享存储?
发布于 2022-09-15 12:50:47
经过长时间的搜索,我发现这很容易(通常.)。在我的例子中,我使用Vue.js的渐进方面将应用程序放置在我的HTML代码的不同位置。具体来说,我希望在布局的标题中填充一个购物车图标,其中包含项目的数量。因此,我使用App.vue作为我的产品-应用程序和Basket.vue作为我的篮子指示器。
简单的诀窍是只实例化一次松针。假设您有一个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>在您的Basket.vue中也是如此:
<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“
https://stackoverflow.com/questions/73308016
复制相似问题