Reputation: 1
I am trying to display an array with v-for in 1 line which is working but I want to add "," in between every word. The only problem is when I do this it will end with an "," too. Any suggestions?
Upvotes: 0
Views: 697
Reputation: 90013
.join()
joins strings with the specified "glue" (comma
+ space
in this case):
new Vue({
el: '#app',
data: () => ({
items: ['apple', 'banana', 'cherry']
}),
computed: {
displayItems() {
return this.items.join(', ');
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
Items: {{ displayItems }}
</div>
One could even argue that, given it's a very simple case, you shouldn't bother with a computed
:
new Vue({
el: '#app',
data: () => ({
items: ['apple', 'banana', 'cherry']
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
Items: {{ items.join(', ') }}
</div>
If you really want to use tags, you can solve the problem using CSS pseudo elements:
new Vue({
el: '#app',
data: () => ({
items: ['apple', 'banana', 'cherry']
})
})
#app > span:after {
content: ', '
}
#app > span:last-child:after {
content: none
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
Items: <span v-for="(item, key) in items" :key="key" v-text="item"/>
</div>
Upvotes: 2
Reputation: 482
Put the comma inside a <template>
and check if that is the last item
<template>
<div>
<span v-for="(item, index) of items" :key="i">
{{item}}<template v-if="index !== items.length - 1">,</template>
</span>
</div>
</template>
<script>
export default {
data() {
return {
items: ['test A', 'test B', 'test C']
}
}
}
</script>
Upvotes: 0