Recently moving from Vuex where the concept of rootState
was very handy. From any of the modules, you could have access to other module's actions.
With Pinia, inside a store's actions, I've not been able to access "other stores" any way except the example I find on the Pinia pages where you instantiate the "other store" within each action. const otherStore = useOtherStore().
This is very repetitive. Is there a better less repetitive way?
Here is a working solution that allows stores to be 'used' once and imported into the modules that need them. Included below is some of the code making up the solution.
import { createPinia } from 'pinia'
const pinia = createPinia()
import { useStore1 } from '../store/store1';
import { useStore2 } from '../store/store2';
const store1 = useStore1(pinia)
const store2 = useStore2(pinia)
export { pinia, store1, store2 }
import { defineStore } from 'pinia';
import { pinia, store2 } from '../store'
export const useStore1 = defineStore('store1', {
state: () => {
return {
store1Property: null,
}
},
actions: {
setStore2Property(payload) {
store2.store2Property = payload
console.log('store2Property', store2.store2Property);
},
},
});
<script>
import { pinia, store1, store2 } from './store'
export default {
name: 'App',
mounted() {
store1.setStore2Property('- store2 was set from store1');
store2.setStore1Property('- store1 was set from store2');
},
};
</script>