I am using pinia in my vue3 projects and for some reason I am trying to store some temporary data in pinia, here is 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);
}
}
})
But when I tried to push item into temporary.itemList
in my vue file, it failed:
<script setup lang="ts">
// ...
const useTemplate = useTemplateStore();
// both of them failed
useTemplate.addItem({ ... });
useTemplate.temporary.itemList.push({ ... });
</script>
when I checked the console, it showed: directly push using addItem method
I log the itemList
out(console.log(useTemplate.temporary.itemList)
), and the result is undefined
.
where is the problem? it bothers me very much,so if anyone can help me out I'd appreciate it.
By the way, my projects is coding with typescript.
It could be something caused by TypeScript
.
The JavaScript
version works well.
const { createApp } = Vue
const { createPinia, defineStore } = Pinia
const useTemplateStore = defineStore('template', {
state: () => {
return {
templates: [],
temporary: {
itemList: []
}
}
},
actions: {
reset() {
this.temporary = {
itemList: []
}
},
addItem(item) {
this.temporary.itemList.push(item);
}
}
})
const App = {
setup() {
const useTemplate = useTemplateStore();
// both of them failed
useTemplate.addItem({ item: 1 });
const addItem2 = () => {
useTemplate.temporary.itemList.push({ item: useTemplate.temporary.itemList.length + 1})
}
return {
useTemplate,
addItem2
}
}
}
const app = createApp(App)
const pinia = createPinia()
app.use(pinia)
app.mount('#app')
#app { line-height: 1.75; }
[v-cloak] { display: none; }
<div id="app" v-cloak>
useTemplate.temporary.itemList: {{ useTemplate.temporary.itemList }}<br/>
<button @click="addItem2()">Add Item</button>
<button @click="useTemplate.reset()">Reset</button>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<script src="https://unpkg.com/vue-demi@0.13.11/lib/index.iife.js"></script>
<script src="https://unpkg.com/pinia@2.0.30/dist/pinia.iife.js"></script>