简体   繁体   中英

Vue.js template loop - async axios call

I'm looping over an array and rendering a HTML template, this is working great. For one of the columns I need to perform an additional AJAX call using axios, so per row fetch data.

However after the AJAX call finishes, I can't get the template to update.. I've tried both passing the loop variable in as reference and attempting to return the Promise from axios.

I think I understand the basic premise of how the async calls should work, I just can't find the correct way to set this up within a Vue template/component.

Eg:

<tr v-for="venue in venue_results" :key="venue.id">
    <td class="border px-4 py-2">{{ venue.name }}</td>
    <td class="border px-4 py-2">{{ getCampsCount(venue) }} {{ venue.camps_count }}</td>
    <!-- <td class="border px-4 py-2">{{ venue.active_events }}</td> -->
</tr>
<script>
    export default {
        ...
        methods: {
            ...
            async getCampsCount(venue) {
                console.log(venue);

                let camps_count = '...';
                venue.camps_count = '...';

                let this_venue = venue;

                return axios.get(
                    route('api3.venue-courses', {venue: venue.id}),
                    {
                        params: {
                            type: 'Hol',
                            active: 1,
                        },
                    }
                )
                .then(response => {
                    console.log(response.data.meta.total);

                    camps_count = response.data.meta.total;
                    this_venue.camps_count = response.data.meta.total;

                    return camps_count;
                })
                .catch(error => {
                    camps_count = 'n/a';
                    this_venue.camps_count = 'n/a';

                    return camps_count;
                })
                .then(() => {
                    // Always run
                    return camps_count;
                });
            },
        }
    }
</script>

Use a reference in the loop and access it via index.

<div ref='target' />
this.$refs.target[theIndex].innerText = 'The Value'

You can also create a data member, bind to that, and update in your async handler.

<div>{{results[venue.id]}}</div>
this.results[venue.id] = 'The Value'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM