Ad

Dynamic Array Name In V-for Loop

- 1 answer

Is it possible to make the array in v-for dynamic? Like this:

<div v-for="(company, index) in arrayName">
    ....
</div>

Data:

data() {
    return {
        companies: [],
        arrayName: 'companies'
    }
},
Ad

Answer

My initial reaction would be to question why you're doing this!

If you're sure that this is what you want, you could use a computed property:

computed: {
    things() {
        return this.$data[this.arrayName];
    }
}

Then your template can just loop on things.

However, I would probably go for another approach. Based on the discussion in the comments, an approach using a filter could be:

data() {
    companies,
    filterActive: false
},
computed: {
    things() {
        if (this.filterActive) {
            return this.companies.filter(company => company.isActive);
        }

        return this.companies
    }
}

I assume that the array of companies contain some data that you can use to determine whether they are active or not.

Now all your button needs to do is toggle filterActive between true and false.

Ad
source: stackoverflow.com
Ad