简体   繁体   中英

what is wrong with this async function in Vue3?

It's quite a simple concept error, but anyway I'm not being able to solve it, I'm making an axios.get() in a onMounted hook, inside the block of the onMounted everything is showing correct ⇾ an Array of three objects. But once I return it to the template and interpolate it to see the value is just an empty Array.
here's the code:

<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>

And here's the log and interpolation image: 在此处输入图像描述

Try to use Object.assign to mutate the reactive data:

 Object.assign(events, response.data)

Or define a state using reactive and define events as field:

let state = reactive({
  events:[]
})
...
state.events = response.data

events is overwritten with response.data , which effectively removes the original reactive() instance from the component's context:

let events = reactive<Event[]>([])

onMounted(async () => {
  ⋮
  events = response.data // ❌ `events` is now the same as `response.data`,
                         // and the original value is gone!
})

Note: Using const here usually prevents these mistakes:

const events = reactive<Event[]>([]) // 👍 const prevents accidental overwrites like above

Solution

One solution is to declare events as a ref instead of reactive :

const events = ref<Event[]>([])

onMounted(async () => {
  ⋮
  events.value = response.data // ✅ `events.value` is now the same value as `response.data`
})

demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM