vue:关于异步请求导致页面不渲染问题的解决

最近在vue中使用axios请求时获取后端数据时,发现因为后端返回数据需要时间,导致页面渲染时没有拿到数据,数据无法渲染出来。

在网上试了各种方法都不行,以下是代码:

页面:  

  <table width="300px" border="0px">

        <tr v-for="(item) in historyLists.slice(0, 3)" height="30px" οnclick="location.href='#';">

            <td><file-text-outlined style="color: darkcyan; font-size: 18px;" /></td>

            <td class="subSystem_td">{ { item.subSystem }}</td>

            <td class="timestamp_td"> { { item.timestamp }}</td>

            <td><span class="comment_td">{ { item.comment }}</span></td>          

        </tr>

    </table>

扫描二维码关注公众号,回复: 16481741 查看本文章

import axios from 'axios';

import { reactive } from 'vue';

import { onMounted } from 'vue'

interface historyListDataItem {

    key: number;

    subSystem: string;

    releaseVersion: string;

    timestamp: string;

    comment: string;

}

let historyLists: historyListDataItem[] = []

const getData = async () => {

    let mydata = await axios.get('/CheckCorporateResult/Test_histroyList.json')

        .then(

            (res) => {

                for (let i = 0; i < res.data.data.length; i++) {

                    historyLists.push({

                        key: i,

                        subSystem: res.data.data[i].subSystem,

                        releaseVersion: res.data.data[i].releaseVersion,

                        timestamp: res.data.data[i].timestamp,

                        comment: res.data.data[i].comment

                    })

                }

            }

        )

}

export default ({

    setup() {

        getData()

        return {

            getData,

            historyLists

        };

    }

});

可以看出试了很多方法,最后发现是变量定义的错误。

代码中标红的部分改成:

const historyLists = reactive<Array<historyListDataItem>>([])

因为只有将其声明为reactive或是ref类型,它才是一个响应式的变量,才能在自身值改变时重新渲染页面。

具体可以参考官网:响应式基础 | Vue.js (vuejs.org)

猜你喜欢

转载自blog.csdn.net/defined_/article/details/130555143
今日推荐