Using vue.js and v-for I want to generate a list of <span>
elements that are separated by ", ".
Is there a simple solution for this in vue.js?
In JavaScript I would do a users.join(", ")
.
Or in FreeMarker templates you can use quite fancy things with lists I enjoy to use, e.g.
<#list users as user>
<span>
${user}<#sep>, </#sep>
</span>
<#else>
<p>No users</p>
</#list>
In vue I haven't discovered something similar yet. (Well, the else
-part can be done using v-if and v-else of course.) Did I miss something?
Or what would be an alternative solution? I was thinking of using a template a generate the separator if this is not the last index by comparing the current index with the length of the array. However, this wouldn't work if I iterate over the properties of an object.
Yes. It requires using the <template>
element as a no-tag container and the index
property in the list.
<div>
<template v-for="(user, index) in users">
<template v-if="index > 0">,</template>
<span>{{user}}</span>
</template>
</div>