Vue3 中的这个异步函数有什么问题?
2022-07-31
1008
这是一个相当简单的概念错误,但无论如何我都无法解决它,我在 onMounted 钩子中创建了一个 axios.get(),在 onMounted 块内,一切都显示正确⇾一个由三个对象组成的数组。但是,一旦我将其返回到模板并对其进行插值,就会看到该值只是一个空数组。
这是代码:
<template>
<div class="container">
<h1>Events for good</h1>
<img alt="Vue logo" src="../assets/logo.png" />
<EventCard v-for="event in events" :key="event.id" :event="event"/>
{{ events }}
</div>
</template>
<script lang="ts">
import { defineComponent, onMounted, reactive } from 'vue';
import { Event } from '@/types/event';
import EventCard from '@/components/EventCard.vue';
import axios from 'axios';
export default defineComponent({
name: 'EventList',
components: {
EventCard
},
setup() {
let events = reactive<Event[]>([])
onMounted( async() => {
const response = await axios.get('http://localhost:3000/events');
console.log(response.data)
events = response.data
console.log(events)
})
return {
events
}
}
});
</script>
2个回答
events
被
response.data
覆盖,这实际上会从组件上下文中删除原始
reactive()
实例:
let events = reactive<Event[]>([])
onMounted(async () => {
⋮
events = response.data // ❌ `events` is now the same as `response.data`,
// and the original value is gone!
})
注意
:在此处使用
const
通常可以避免这些错误:
const events = reactive<Event[]>([]) // 👍 const prevents accidental overwrites like above
解决方案
一种解决方案是将
events
声明为
ref
,而不是
reactive
:
const events = ref<Event[]>([])
onMounted(async () => {
⋮
events.value = response.data // ✅ `events.value` is now the same value as `response.data`
})
tony19
2022-07-31
尝试使用
Object.assign
来改变反应数据:
Object.assign(events, response.data)
或者使用反应定义状态并将
events
定义为字段:
let state = reactive({
events:[]
})
...
state.events = response.data
Boussadjra Brahim
2022-07-31