Sometimes, we want to output a comma separated array with Vue.js.
In this article, we’ll look at how to output a comma separated array with Vue.js.
How to output a comma separated array with Vue.js?
To output a comma separated array with Vue.js, we can check the index of the item we’re rendering and add a comma if we aren’t rendering the first item.
For instance, we write
<template>
<div>
<span v-for="(element, index) in list" :key="element">
<span v-if="index !== 0">, </span><span>{{ element }}</span>
</span>
</div>
</template>
<script>
//...
export default {
//...
data() {
return {
list: ["john", "fred", "harry"],
};
},
//...
};
</script>
to render the list
items with v-for
.
We add a comma before the element
being rendered if the index of them
element` isn’t 0 to add a comma before all items except the first.
Conclusion
To output a comma separated array with Vue.js, we can check the index of the item we’re rendering and add a comma if we aren’t rendering the first item.