I'm currently diving into my first Vue project after working with React and vanilla JavaScript. I'm still trying to grasp a few concepts in Vue, such as importing state and action props from a Pinia store. It seems like I have to import these multiple times within a single Vue component, which is different from how it works in React.
In this scenario, I am bringing in a simple count value and an increment function, attempting to utilize them in various parts of the component:
<script setup>
// Initially, I import everything in setup, where I can access props (currentCount and incrementCount) in my template:
import { storeToRefs } from 'pinia';
import { useStore } from '@/stores/store';
const { currentCount } = storeToRefs(useStore());
const { incrementCount } = useStore();
</script>
<template>
<main>
Current count: {{ currentCount }}
<button @click="incrementCount">Increment</button>
</main>
</template>
<script>
// I cannot directly use store values from setup here.
// This statement does not work:
// console.log(currentCount);
// I also face errors when importing store values here.
// I receive the following error message:
// "getActivePinia was called with no active Pinia"
// const { currentCount } = storeToRefs(useStore());
export default {
mounted() {
// I have to re-import store values here for them to work correctly:
const { currentCount } = storeToRefs(useStore());
console.log(currentCount);
},
watch: {
// Surprisingly, this reference to watching "currentCount" works fine:
currentCount() {
// Again, I need to import store values here for them to function properly:
const { currentCount } = storeToRefs(useStore());
console.log(currentCount);
},
},
};
</script>
It's evident that to utilize store values in my template, during mount, and in a watcher (similar to React's useEffect hook), I have to import the store props three times. Is this standard practice? Is there a more straightforward way to achieve what I'm aiming for, where I only need to import props once? I want to ensure I haven't overlooked anything and that I'm following conventional practices.
Appreciate any assistance and guidance!