【问题标题】:Reactive data in vue composition api is not rendered in templatevue composition api中的反应性数据未在模板中呈现
【发布时间】:2021-03-05 21:07:16
【问题描述】:

我希望我能找到为什么这不起作用的答案。我正在尝试从 api 获取数据并将其显示在 vue 模板上。这是我的代码(摘要)。

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

使用此代码,我可以在控制台中看到提取的“歌曲”,但它没有呈现在页面中。我已经尝试过 onBeforeMount、onRenderTriggered、onUpdated,但都没有工作。我似乎无法弄清楚这一点。

【问题讨论】:

    标签: javascript vue.js vuejs3 vue-composition-api vue-reactivity


    【解决方案1】:

    reactive 应该有一个对象作为参数:

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

    【讨论】:

    • 嘿@boussadjra-brahim,谢谢伙计!我以前尝试过这种方法,但没有奏效。我想我的错误是让song 成为一个对象而不是一个数组,因为response.data.results[0].category_tracks 应该是一个可迭代的数组,对吧?
    • 不客气,是的,它应该是一个数组并嵌套在传递给响应式的对象中,请不要忘记支持我的回答
    • 不应该是state.songs = response.data.results[0].category_tracks吗?
    • 我还注意到,如果我尝试将songs 分配给另一个变量,如let songs = state.song 或返回{ songs: state.songs },那么它将不会在模板中呈现。这是为什么?如果我的问题听起来很愚蠢,我很抱歉,我对 vue 及其 composition-api 有点陌生。
    • @yom-s,你是对的。应该是state.songs = response.data.results[0].category_tracks
    猜你喜欢
    • 2022-10-19
    • 1970-01-01
    • 2019-11-13
    • 2021-08-25
    • 2021-06-08
    • 1970-01-01
    • 2022-11-14
    • 2021-10-17
    • 1970-01-01
    相关资源
    最近更新 更多