The Pinia documentation mentions using plugins to augment stores by adding properties as follows:
pinia.use(({ store }) => {
store.hello = 'world'
})
Then wherever you use the store, you can access store.hello as follows:
const myStore = useMyStore()
console.log(store.hello)
I believe you can also access the augmented property from inside an Options store with this.hello. But I see no way to access this from inside a setup store. For example:
import { defineStore } from 'pinia'
export const useProductStore = defineStore('products', () => {
function getProducts() {
???.hello // <<<---- How do I access the augmented property here?
}
return { getProducts }
})
The short answer is to define a state variable with the exact name of hello and start using that:
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';
export const useProductStore = defineStore('exampleStore', () => {
const hello = ref(''); // << will be filled with the plugin installation
const comp = computed(() => {
return hello.value;
});
function getProducts() {
return hello.value;
}
return {getProducts, comp, hello};
});
Explanation:
If you want to add new state properties to a store or properties that are meant to be used during hydration, you will have to add it in two places:
So, you'd better attach variables to store.$state.
I have provided you with a live example.
const { createApp, ref, computed } = Vue;
const { createPinia, defineStore } = Pinia;
const useProductStore = defineStore('exampleStore', () => {
const hello = ref(''); // <<-- will be the value passed through in plugin installation
const comp = computed(() => {
return hello.value;
});
function getProducts() {
return hello.value;
}
return {getProducts, comp, hello};
});
const app = createApp({
setup() {
const store = useProductStore();
const comp = store.comp;
const prod = store.getProducts();
return {
comp,
prod,
}
}
});
const pinia = createPinia();
pinia.use(({store}) => {
store.$state.hello = 'World of lions'
// store.hello = 'world of lions (avoid)';
});
app
.use(pinia)
.mount('#app');
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="https://unpkg.com/vue-demi"></script>
<script src="https://unpkg.com/pinia"></script>
<div id="app">
<p> <i> computed </i> Hello {{ comp }} </p>
<p> <i> function </i> Hello {{ prod }} </p>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With