Vue - check if you are on the last prop of a v-for loop
If I have the following data property:
person: {name: 'Joe', age: 35, department: 'IT'}
And wanted to loop through and output it as follows:
name: Joe, age: 35, department: IT
So far I have:
<span v-for="(val, key) in person">{{key}}: {{val}}, </span>
But this displays:
name: Joe, age: 35, department: IT,
with an extra comma on the end, how can I have it detect that it's the last prop and not show the comma? I thoughta v-show or v-if may be the solution but can't quite figure out how to make it work.
Solution 1:
Here is one way.
<span v-for="(val,key,index) of person">
key: {{key}}, val: {{val}}, index: {{index}}
<span v-if="index != Object.keys(person).length - 1">, </span>
</span>
Solution 2:
Here's a solution if you're looping through an array, rather than an object:
<div id="app">
<div v-for="(item, index) in items">
<div v-if="index == items.length - 1">yes</div>
{{ item }}, {{ index }}
</div>
</div>
Solution 3:
You can also "cheat" by inserting the comma before each item, as it's easier to check for the first item (index !== 0
).
<span v-for="(val, key, index) in person">
<span v-if="index !== 0">, </span>
{{key}}: {{val}}
</span>
Solution 4:
You can do that with a computed
to see if the current index (third parameter forv-if
) is the last property:
computed: {
last(){
return Object.keys(this.person).length-1;
}
}
Then in your v-for
:
<span v-for="(val, key, index) in person">{{key}}: {{val}}<span v-if="index !== last">, </span> </span>
Here's the JSFiddle: https://jsfiddle.net/wv2ujxvn/