我只需要重复标签 5 次。我阅读了文档,但没有意识到如何做这样的事情:
<some-tag>
<star repeat={5} />
</some-tag>
我只发现了这种丑陋的方式:
<some-tag>
<star each={stars} />
this.stars = new Array(5);
</some-tag>
最佳答案
查看源代码后,this您可能会感兴趣。
如果您计划使用 each
属性,你必须定义某种数组让 riot 传递给 forEach
.
这jsfiddle是另一个想法(不是最优的),但我认为它说明了这一点。另一个解决方案是使用 Riot 的 mixin
系统构建某种 repeat
属性:
https://jsfiddle.net/aunn3gt0/2/
在您尝试使用 <yield/>
之前,这是一个很好的解决方案标签。那么它可能需要进行调整。这是它的工作原理:
var repeat = {
init: function() {
var repeats = [],
count = this.opts.repeat
this.on('mount', function() {
if (!count) return
var impl = this.root.innerHTML
this.root.removeAttribute('repeat')
while(repeats.length < count) {
var clone = this.root.cloneNode()
this.root.parentNode.insertBefore(clone, this.root)
clone.innerHTML = impl
repeats.push(riot.mount(clone))
}
})
this.on('unmount',function(){
repeats.forEach(function(tag,i){
tag.unmount()
})
})
}
}
然后用this.mixin(repeat)
附加它并按照您的预期使用它:
<tag repeat="10">Repeated 10 times.</tag>
关于javascript - Riot.js 如何重复标记一定次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34384830/