无法使用 Pinia Store 从状态检索数据
我正在尝试使用 Vue3 克服组合 API 和 Pinia。
我正在调用外部 API 来获取一些数据并将其存储在商店的状态中,我的问题是,当我从页面调用此状态时,它似乎是空的,我无法检索我在商店的操作部分中调用的数据。我在这个过程中有什么错误的想法吗?
App.vue
<template>
<h1>Rick And Morty</h1>
<ul>
<li v-for="(item, index) in characters" :key="index">
{{item}}
</li>
</ul>
</template>
<script>
import { useCharactersStore } from '@/stores/characters'
import { onBeforeMount } from 'vue'
export default {
setup() {
const useStore = useCharactersStore()
const characters = useStore.characters
console.log("Store: " + characters)
onBeforeMount(() => {
useStore.fetchCharacters()
})
return {
useStore,
characters
}
},
}
</script>
character.js
import { defineStore } from 'pinia'
export const useCharactersStore = defineStore('main', {
state: () => {
return {
characters: [],
page: 1
}
},
actions: {
async fetchCharacters() {
const res = await fetch('https://rickandmortyapi.com/api/character/')
const { results } = await res.json()
this.characters.push(results)
console.log("Back: " + this.characters)
}
}
})
I'm trying to get over the composition API and Pinia with Vue3.
I'm making a call to an external API to fetch some data and store it in the state of the store, my issue here is that when I call this state from my page, it appears to be empty and I can't retrieve the data that I've been calling in the actions section of my store. Any ideas where I'm wrong in the process?
App.vue
<template>
<h1>Rick And Morty</h1>
<ul>
<li v-for="(item, index) in characters" :key="index">
{{item}}
</li>
</ul>
</template>
<script>
import { useCharactersStore } from '@/stores/characters'
import { onBeforeMount } from 'vue'
export default {
setup() {
const useStore = useCharactersStore()
const characters = useStore.characters
console.log("Store: " + characters)
onBeforeMount(() => {
useStore.fetchCharacters()
})
return {
useStore,
characters
}
},
}
</script>
character.js
import { defineStore } from 'pinia'
export const useCharactersStore = defineStore('main', {
state: () => {
return {
characters: [],
page: 1
}
},
actions: {
async fetchCharacters() {
const res = await fetch('https://rickandmortyapi.com/api/character/')
const { results } = await res.json()
this.characters.push(results)
console.log("Back: " + this.characters)
}
}
})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是整个
results
数组作为一个元素插入到characters
中:将所有
results
推入characters
作为单个数组元素,使用 扩展运算符(即...结果
):演示
The problem is the entire
results
array is inserted intocharacters
as one element:To push all
results
intocharacters
as individual array elements, use the spread operator (i.e.,...results
):demo