如何在Vue模板中显示异步数据 [英] How to display async data in vue template

查看:809
本文介绍了如何在Vue模板中显示异步数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在显示异步加载的vue模板数据的情况下,我很有趣.在我的特定情况下,我需要显示产品对象的标题属性:

I'm interesting in the case of displaying in vue template data which loaded asynchroniously. In my particular situation I need to show title attribute of product object:

<td class="deals__cell deals__cell_title">{{ getProduct(deal.metal).title }}</td>

但是该产品当前未加载,因此标题根本不会呈现.我找到了一个可行的解决方案:如果未加载产品,则在解决诺言之后,请调用getProduct函数:

But the product isn't currently loaded so that the title isn't rendered at all. I found a working solution: if the products aren't loaded then recall getProduct function after the promise will be resolved:

getProduct (id) {
  if (!this.rolledMetal.all.length) {
    this.getRolledMetal()
      .then(() => {
        this.getProduct(id)
      })
    return {
      title: ''
    }
  } else {
      return this.getRolledMetalById(id)
  }
}

但是也许您知道更优雅的解决方案,因为我认为这有点复杂:)

However maybe you know more elegant solution because I think this one is a little bit sophisticated :)

推荐答案

在加载数据时,我总是使用加载器或微调器!

I always use a loader or a spinner when data is loading!

<template>
    <table>
        <thead>
            <tr>
                <th>One</th>
                <th>Two</th>
                <th>Three</th>
            </tr>
        </thead>
        <tbody>

            <template v-if="loading">
                <spinner></spinner> <!-- here use a loaded you prefer -->
            </template>

            <template v-else>
                <tr v-for="row in rows">
                    <td>{{ row.name }}</td>
                    <td>{{ row.lastName }}</td>
                </tr>
            </template>

        </tbody>
    </table>
</template>

和脚本:

<script>
    import axios from 'axios'
    export default {
        data() {
            return {
                loading: false,
                rows: []
            }
        },
        created() {
            this.getDataFromApi()
        },
        methods: {
            getDataFromApi() {
                this.loading = true
                axios.get('/youApiUrl')
                .then(response => {
                    this.loading = false
                    this.rows = response.data
                })
                .catch(error => {
                    this.loading = false
                    console.log(error)
                })
            }
        }
    }
</script>

这篇关于如何在Vue模板中显示异步数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆