Gordon Freeman Turtle Gordon Freeman Turtle - 11 months ago 125
HTML Question

Splitting a comma-seperated string in a v-for method

I'm trying to split a string on each comma using a

v-for
method from Vue.js.

Input:
tags: 'test1, test2, test3'


Method:
<span v-for="tag in tags" v-text="tag"/>


Output:
t e s t 1 , t e s t 2 , t e s t 3


Desired output:
test1 test2 test3


How could I split the comma-separated text correctly? I cannot access 'tags' input unless I am in a
v-for
loop in order to call
object.tags
.

Not sure why this does not work although It's pretty much the same thing in my code: https://jsfiddle.net/9o3o11jc/1/

Answer Source

You can do string manipulation to turn it into an array of words.

new Vue({
  el: '#app',
  data() {
    return {objects:[{tags: 'test1, test2, test3'}]}
   },
   methods: {
      splitJoin(theText){
      	return theText.split(', ');
      }
   } 
});
<script src='https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.min.js'></script>
<div id="app">
  <div v-for="object in objects">
    <span v-for="tag in splitJoin(object.tags)" v-text="tag"></span>
  </div>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download