AngeloC
AngeloC

Reputation: 3513

Can we use v-for in a custom component's template in vuejs?

use following code in html, it works:

<div v-for="i in [1,2,3]" >{{i}}</div>

but when used in a component template:

Vue.component('test', {    
    template: '<div v-for="i in [1,2,3]" >{{i}}</div>'
})

It will trigger an error:

- Cannot use v-for on stateful component root element because it renders  multiple elements.

any idea putting a v-for in this situation? Thanks,

Upvotes: 4

Views: 5653

Answers (1)

CodinCat
CodinCat

Reputation: 15914

Because doing that, the result of test component will become

<div>1</div>
<div>2</div>
<div>3</div>

A component must have a root element. Adding a root <div> then it should work:

Vue.component('test', {    
    template: '<div><div v-for="i in [1,2,3]" >{{i}}</div></div>'
})

output:

<div>
  <div>1</div>
  <div>2</div>
  <div>3</div>
</div>

Upvotes: 6

Related Questions