Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

javascript - How to display async data in vue template

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>

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 :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

And the script:

<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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...