Learning Junior
Learning Junior

Reputation: 1

V-for in 1 line with something in between

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

Answers (2)

tao
tao

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

dxlliv
dxlliv

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

Related Questions