[英]Pinia action not uploading array of object state (Vue 3)
I am using Vue 3 and Pinia, and I have a store cards.js
, like this one:我正在使用 Vue 3 和 Pinia,我有一个商店
cards.js
,就像这个:
import { defineStore } from 'pinia'
import { useLanguageStore } from './language'
import axios from 'axios'
export const useCardsStore = defineStore({
id: 'cards',
state: () => ({
cards: []
}),
actions: {
async generateCards() {
const languageStore = useLanguageStore();
this.cards = (await axios({
method: "post",
url: "<endpoint>", // some endpoint
data: {
text: languageStore.sentence,
language: languageStore.language
}
})).data.map(token => ({
text: token.text,
pos: token.pos,
}));
console.log(this.cards) // see (*)
}
}
})
Then, inside a component, I use something like this:然后,在一个组件中,我使用这样的东西:
<template>
...
<input v-model="sentence">
<button @click.prevent="generateCards()">Generate</button>
...
</template>
<script setup>
import { storeToRefs } from 'pinia'
import { useCardsStore } from '../stores/cards'
import { useLanguageStore } from '../stores/language'
const { cards } = storeToRefs(useCardsStore())
const { sentence } = storeToRefs(useLanguageStore())
const { generateCards } = useCardsStore()
</script>
However, even though when I click in the button, console output after mofifying this.cards
(*) is:然而,即使当我点击按钮时,控制台 output 在 mofifying
this.cards
(*) 之后是:
Proxy {0: {…}, 1: {…}, 2: {…}, 3: {…}}
[[Handler]]: Object
[[Target]]: Array(4)
0: {text: 'esto', pos: 'PRON'}
1: {text: 'es', pos: 'VERB'}
length: 2
[[Prototype]]: Array(0)
[[IsRevoked]]: false
(Hence the array is being correctly generated) Inside of Vue devtools I can see the state cards
has not changed (as well as I can see it in the application). (因此数组被正确生成)在 Vue devtools 内部,我可以看到 state
cards
没有改变(我可以在应用程序中看到它)。
Any help would be appreciated.任何帮助,将不胜感激。 Thank you.
谢谢你。
The answer was provided by @Phil .答案由@Phil提供。 In the docs there is a link about not destructuring the store.
在文档中有一个关于不破坏商店的链接。 The correct way was to change
正确的方法是改变
const { generateCards } = useCardsStore()
to到
const store = useCardsStore()
and use store.generateCards
instead of store
in the template.并使用
store.generateCards
而不是在模板中store
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.