Sometimes we may want to display items from an array separated by a comma. We know that displaying an array directly in the template will also include the square brackets.
We can only show the contents of the list in the array separated by commas as follows:
<script setup>
import { ref, computed } from 'vue'
const names = ref(['Gautam', 'John', 'Tom', 'Frank'])
const commaSeparatedNames = computed(() => {
return names.value.join(',')
})
</script>
<template>
<div>
<div>
{{ commaSeparatedNames }}
</div>
</div>
</template>
Code language: HTML, XML (xml)
The above code will output the following:
Gautam,John,Tom,Frank
Of course, we can add some space after the comma by adding some space to the join method on line 7 as follows:
return names.value.join(', ')
Code language: JavaScript (javascript)
We can even separate the list items with dashes (-) if we want to.
return names.value.join(' - ')
Code language: JavaScript (javascript)
The list would then look like this:
If you have any doubts about the join() method, sound off in the comments below!