Checking array length

Published 1 month ago by kreierson

I have a vue component with an initial data property set to an empty array.

data: function() {
            return {
                trips: [],
        }
}

Then in the mounted hook, I do a request and populate that array.

In my vue template, I want to show a table of the results if the trips array has any trips in it, and I want to show a div saying there are no trip available if the array is empty.

I am currently doing this

<table class="table table-borderless" v-show="trips.length">
    Table data
</table>

<p v-show="!trips.length">No trips available</p>

The no trips available paragraph always shows up, event though I can see there are trips available in the Vue devtools. I understand it's probably initializing as an empty array, but shouldn't Vue pick up on the change and display the results when the array is eventually populated? How do I solve this?

Thanks!

Best Answer (As Selected By kreierson)
kreierson

Figured it out. I forgot I was using reduce on the array to group the trips by date, which turned the trips array into an object.

self.trips = response.data.trips.reduce(function(r, a) {
                        r[a.start_date] = r[a.start_date] || [];
                        r[a.start_date].push(a);
                        return r;
                    }, Object.create(null));

I did this in case anyone else comes across this.

self.hasTrips = response.data.trips.toString();

Then did my v-show on the hasTrips property.

kreierson

PS, I am not able to pass the trips in as a prop.

tisuchi
tisuchi
1 month ago (265,395 XP)

@kreierson

This might works for you instead of v-show.

<p v-if="trips.length">
    <table class="table table-borderless" v-show="trips.length">
        Table data
    </table>
</p>
<p v-else>No trips available</p>
kreierson

Figured it out. I forgot I was using reduce on the array to group the trips by date, which turned the trips array into an object.

self.trips = response.data.trips.reduce(function(r, a) {
                        r[a.start_date] = r[a.start_date] || [];
                        r[a.start_date].push(a);
                        return r;
                    }, Object.create(null));

I did this in case anyone else comes across this.

self.hasTrips = response.data.trips.toString();

Then did my v-show on the hasTrips property.

kreierson

@tisuchi Thanks for the reply! Turns out I was an idiot and forgot I converted the array to an object :p

Please sign in or create an account to participate in this conversation.