[Vuejs]-How to "join" elements in Vue with a separator?

1👍

Without box class, you can use javascript split and join function

new Vue({
  el: "#app",
  data: {
    boxes: ['hello', 'world', 'bonjour']
  },
})
#app {
  display: flex;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="box in boxes.join(' →').split(' ')" class="">{{box}}</div>
</div>

In your existing code

new Vue({
  el: "#app",
  data: {
    boxes: [1, 2, 3]
  },
})
#app {
  display: flex;
}

.box {
  background-color: red;
  width: 60px;
  height: 30px;
  margin: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="box,index in boxes" class="">
      <span class="box">Hello</span><span v-if="index<boxes.length-1">=></span>
  </div>
</div>

-1👍

This is not a Vue specific problem, you can use Array.prototype.join() to insert a separator between array items.

In your use case, you may create a computed property like this

new Vue({
  el: "#app",
  data: {
    boxes: [1, 2, 3]
  },
  computed: {
    // returns '1→2→3'
    boxesWithSeparator() {
      return this.boxes.join('→')
    }
  }
})

Leave a comment