我们可以在vuejs中的自定义组件模板中使用v-for吗?

Ang*_*loC 4 vue.js

在html中使用以下代码,它可以正常工作:

<div v-for="i in [1,2,3]" >{{i}}</div>
Run Code Online (Sandbox Code Playgroud)

但是在组件模板中使用时:

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

它将触发错误:

- Cannot use v-for on stateful component root element because it renders  multiple elements.
Run Code Online (Sandbox Code Playgroud)

有什么想法在这种情况下提出v-for吗?谢谢,

Cod*_*Cat 5

因为这样做,test组件的结果将变为

<div>1</div>
<div>2</div>
<div>3</div>
Run Code Online (Sandbox Code Playgroud)

组件必须具有根元素。添加一个根<div>然后它应该工作:

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

输出:

<div>
  <div>1</div>
  <div>2</div>
  <div>3</div>
</div>
Run Code Online (Sandbox Code Playgroud)