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>

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)

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值