【问题标题】:VueJS handle multiple promise on page loadVueJS 在页面加载时处理多个承诺
【发布时间】:2019-03-06 22:17:36
【问题描述】:

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

我有一个 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 重新加载时,它可以工作......

有什么想法吗?

【问题讨论】:

    标签: javascript vue.js promise loading


    【解决方案1】:

    我认为是因为您尝试使用then 的另一个then 的响应

    试试看

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

    您需要将getLabel 添加到mounted 函数中

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

    【讨论】:

    • 我已经试过了,还是一样的问题。它适用于 HMR,但不适用于整页重新加载 (F5)
    • HMR 是什么意思?
    • 模块热更换
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-02
    • 1970-01-01
    • 1970-01-01
    • 2020-10-25
    • 2014-11-22
    相关资源
    最近更新 更多