简体   繁体   中英

Reactive data in vue composition api is not rendered in template

I hope I find an answer to why this is not working. I'm trying to fetch data from an api and display it on vue template. Here's my code (summarized).

<template>
 <div v-for="song in songs" :key="song.id" class="custom-card" @click="addAudio($event, song)">
  {{ song }}
 </div>
</template>

<script>
const axios = require('axios').default
import { reactive, onMounted } from 'vue'

export default {
        name: 'SongCarousel',
        props: {          
            carouselUrl: String,
        },
        setup(props) {
            let songs = reactive({})
           // const data = localState.value

            onMounted(
                axios
                    .get(props.carouselUrl)
                    .then(response => {
                        songs = response.data.results[0].category_tracks
                        console.log(songs)
                    })
            )

            return {
                songs,
            }
        },
</script>

With this code, I can see the fetched 'songs' in the console but it's not rendered in the page. I have tried onBeforeMount, onRenderTriggered, onUpdated but none is working. I can't seem to figure this out.

reactive should have an object as parameter :

<template>
 <div v-for="song in state.songs" :key="song.id" class="custom-card" @click="addAudio($event, song)">
  {{ song }}
 </div>
</template>

<script>
const axios = require('axios').default
import { reactive, onMounted } from 'vue'

export default {
        name: 'SongCarousel',
        props: {          
            carouselUrl: String,
        },
        setup(props) {
            let state= reactive({songs:[]})
         

            onMounted(()=>{
             axios
                    .get(props.carouselUrl)
                    .then(response => {
                        state.songs = response.data.results[0].category_tracks
                        console.log(state.songs)
                    })
                
            })

            return {
                state,
            }
        },
</script>

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