supercoolville
supercoolville

Reputation: 9086

How do I get the count for each item using v-for in Vue?

I have this Vue code:

var itembox = new Vue({
    el: '#itembox',
    data: {
        items: {
            cookiesncreme: {
                name: "Cookies N Cream",
                description: "description"
            },
            chocolateswirl: {
                name: "Chocolate Swirl",
                description: "description"
            },
            peanutbutter: {
                name: "Peanut Butter",
                description: "description"
            }
        }
    }
});

And this HTML code:

<div id="itembox">
    <div v-for="(item, index) in items">{{ index }} - "{{ item.name }}"</div>
</div>

I am trying to output the code in a numbered list, for example:

<div>1 - Cookies N Creme</div>
<div>2 - Chocolate Swirl</div>
<div>3 - Peanut Butter</div>

But since my items have keys already, it comes out like this:

<div>cookiesncreme - Cookies N Creme</div>
<div>chocolateswirl - Chocolate Swirl</div>
<div>peanutbutter - Peanut Butter</div>

Is there any other way to get a number count for each item? Thanks!!

Upvotes: 2

Views: 5899

Answers (2)

reinerBa
reinerBa

Reputation: 1660

Accourding to the documentation Vue API: v-for

Alternatively, you can also specify an alias for the index (or the key if used on an Object):

<div v-for="(item, index) in items"></div>
<div v-for="(val, key) in object"></div>
<div v-for="(val, key, index) in object"></div>

Upvotes: 1

Chad Campbell
Chad Campbell

Reputation: 937

In Vue.js, there's actually a third parameter that you can pass in this case. For example, you could do this:

<div id="itembox">
    <div v-for="(item, index, i) in items">{{ i+1 }} - {{ index }} - "{{ item.name }}"</div>
</div>

Notice how I used the i parameter, which is actually the index number. I've created a working Fiddle of this here. If you would like to learn more about Vue.js, I hope you'll checkout my Vue.js training course. If this answer helped, I hope you'll mark it as such and vote this item up.

Upvotes: 4

Related Questions