Pinia has been a crucial part of my Vue3 projects, and I've encountered a dilemma while trying to store temporary data in Pinia. Here's a snippet from my store file:
// template.ts
export const useTemplateStore = defineStore('template', {
state: () => {
return {
templates: [] as Template[],
temporary: {
id: generateUUID(),
itemList: []
} as Template
}
},
actions: {
reset() {
this.temporary = {
id: generateUUID(),
itemList: []
}
},
addItem(item: TemplateItem) {
this.temporary.itemList.push(item);
}
}
})
However, when attempting to add an item to temporary.itemList
in my Vue file, it didn't work as expected:
<script setup lang="ts">
// ...
const useTemplate = useTemplateStore();
// both of them failed
useTemplate.addItem({ ... });
useTemplate.temporary.itemList.push({ ... });
</script>
Upon checking the console, the following error messages were displayed: directly push using addItem method
After logging out itemList
(
console.log(useTemplate.temporary.itemList)
), it returned as undefined
.
I'm puzzled by this issue and would greatly appreciate any assistance or insights offered.
Just for your information, my projects are coded using TypeScript.