Vue: About the solution to the problem that the page does not render due to asynchronous requests

Recently, when using axios request in vue to obtain back-end data, I found that because it takes time for the back-end to return data, the data was not obtained when the page was rendered, and the data could not be rendered.

I tried various methods on the Internet, but the following is the code:

page:  

  <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

        };

    }

});

It can be seen that many methods have been tried, and finally it is found that the variable definition is wrong.

The part marked in red in the code is changed to:

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

Because only if it is declared as reactive or ref type, it is a responsive variable, and the page can be re-rendered when its own value changes.

For details, please refer to the official website: Responsive Basics | Vue.js (vuejs.org)

Guess you like

Origin blog.csdn.net/defined_/article/details/130555143