首页 > 解决方案 > VueJS 在页面加载时处理多个承诺

问题描述

我已经搜索了很多问题,但仍然没有找到解决方法,所以你是我最后的机会......

我有一个 Vue 组件,他需要在创建时从 API 加载数据,然后在组件中显示这些数据。我之前已经这样做了,没有任何问题,但是对于我正在制作的这个,它不起作用......

<template>
    <thead v-if="loaded">
    <tr>
        <th v-for="label in labels">
            {{label}}
        </th>
    </tr>
    </thead>
</template>

<script>
    import Schema from '../../api/schema'

    export default {
        data() {
            return {
                labels: [],
                loaded: false
            }
        },
        props: {
            fields: Array
        },
        methods: {
            getFieldsLabels: function () {
                return Promise.all(
                    this.fields
                        .map((field) => Schema().getField(field)
                            .then(response => response.getLabel())
                        )
                )
            }
        },
        mounted() {
            this.getFieldsLabels().then(
                response => {
                    this.loaded = true;
                    this.labels = response
                }
            )
        }
    }
</script>

我有多个要传递的承诺,Promise.all但是当我在浏览器上按 F5 时,页面仍然是空白的。但是当它用 HMR 重新加载时,它可以工作......

有任何想法吗 ?

标签: javascriptvue.jspromiseloading

解决方案


我想是因为你试图使用then另一个人的回应then

试试看

        getFieldsLabels: function () {
            return Promise.all(
                this.fields
                    .map((field) => Schema().getField(field))
            )
        }

您需要添加getLabelmounted功能

        this.getFieldsLabels().then(
            response => {
                this.loaded = true;
                this.labels = response.getLabel()
            }
        )

推荐阅读