Gordon Freeman Turtle
Gordon Freeman Turtle

Reputation: 93

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/

Upvotes: 4

Views: 7625

Answers (2)

Steven B.
Steven B.

Reputation: 9362

You can use String.prototype.split() to turn your string 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>

Upvotes: 10

Zooby
Zooby

Reputation: 323

It sounds like you want the split method from javascript and the seperator ", ". The v-for directive is reading the string as a collection of characters, because object.tags is a single string. What you want is a collection of strings, which is what split will return.

Upvotes: 0

Related Questions