Views: 156
Last Modified: 28.04.2022

Pinia was designed to work with several storages in a single application without extra operations.

The example below overviews a modular approach: create two storages and handle them in two different applications simultaneously.

For example, html code has elements with identifiers: application1 and application2. Accordingly, we can verify that data simultaneously will be updated in two applications. First application will show results and the second will change the data.

Important! Pay extra attention to naming in the function defineStore when declaring storages - first parameter must be unique. This can create issue when you are using the same storage for different Vue applications (for example, for two various widgets that must have identical storage structure but contain different data).

<div id="application1"></div>
<div id="application2"></div>

In JS extension:

import { BitrixVue } from 'ui.vue3';
import { createPinia, defineStore, mapState, mapActions } from 'ui.vue3.pinia';

const store = createPinia();

const counterStore = defineStore('counter', {
	state: () => ({
		counter: 0
	}),
	getters: {
        double()
        {
            return this.counter * 2;
        },
    },
	actions: {
        increaseCounter()
        {
            this.counter++;
        },
        decreaseCounter()
        {
            this.counter--;
        }
    },
});

const statusStore = defineStore('status', {
	state: () => ({
		lastAction: 'None'
	}),
	actions: {
        setAction(action)
        {
            this.lastAction = action.toString();
        },
    },
});

const Buttons = {
	methods: {
		increase() {
			this.increaseCounter();
			this.setAction('Plus');
		},
		decrease() {
			this.decreaseCounter();
			this.setAction('Minus');
		},
		...mapActions(counterStore, ['increaseCounter', 'decreaseCounter']),
		...mapActions(statusStore, ['setAction']),
	},
	// language=Vue
	template: `
        <button @click="increase">+</button>
        <button @click="decrease">-</button>
    `
};
BitrixVue.createApp({
	components: {
		Buttons
	},
	template: `
        <Buttons/>
    `
}).use(store).mount('#application1');

const Counter = {
	computed: {
        ...mapState(counterStore, ['counter']),
        ...mapState(statusStore, ['lastAction']),
    },
	template: `
        <div>Click counter — {{ counter }}</div>
        <div>Last action — {{ lastAction }}</div>
    `
};

BitrixVue.createApp({
	components: {
		Counter
	},
	template: `<Counter/>`
}).use(store).mount('#application2');





Courses developed by Bitrix24