APB
APB

Reputation: 337

Vue js How to split string to array and use in v-for list renderer

I want to split a row of a list and use the result in another list statement like this : I actually know that the syntax of Vue list renderer of this type is incorrect but I want to show you what I need!

var app = new Vue({
	el : "#app",
  data : {
    list : [
      {
        'name' : 'aaa',
        'codes' : '111+222+333'
      },
      {
        'name' : 'bbb',
        'codes' : '432+456+678'
      }
    ]
  }
})
<div id="app">
  <div v-for="row in list">
    <p>{{ row.name }}</p>
    <div v-for="code in (row.codes.split('+'))">
      <p>{{ code }}</p>
    <div>
  </div>
</div>

Update: The above code is correct and I had some problems when using filters like this that is wrong :

v-for="code in (row.codes | split('+'))"

Upvotes: 4

Views: 46737

Answers (3)

ThcMago
ThcMago

Reputation: 11

I use in function in method...

<div id="app">
  <div v-for="row in list">
    <p>{{ row.name }}</p>
    <div v-for="code in splitedList(row.codes)">
      <p>{{ code }}</p>
      </div>
  </div>
</div>

new Vue({
  el: "#app",
  data: {
    list : [
      {
        'name' : 'aaa',
        'codes' : '111+222+333'
      },
      {
        'name' : 'bbb',
        'codes' : '432+456+678'
      }
    ]
  },
  computed: {
  },
methods: {  
    splitedList(row){               
              return (row !== null)?row.split('+'):'';
        }
    }

})

Upvotes: 1

user3841678
user3841678

Reputation: 59

v-for="code in row.codes.split('+')"

Upvotes: 4

Roland
Roland

Reputation: 27719

Here is my solution!

<div id="app">
  <div v-for="row in splitedList">
    <p>{{ row.name }}</p>
    <div v-for="code in row.codes">
      <p>{{ code }}</p>
      </div>
  </div>
</div>

new Vue({
  el: "#app",
  data: {
    list : [
      {
        'name' : 'aaa',
        'codes' : '111+222+333'
      },
      {
        'name' : 'bbb',
        'codes' : '432+456+678'
      }
    ]
  },
  computed: {
    splitedList(){
        let newArr = [...this.list]
      newArr.map(el => {
        return el.codes = el.codes.split('+')
      })
      return newArr
    }
  }

})

See it in action

Upvotes: 10

Related Questions