简体   繁体   English

Riot.js 如何重复标记一定次数?

[英]Riot.js How to repeat tag a certain number of times?

I need just repeat tag 5 times.我只需要重复标记 5 次。 I read documentation, but did not realize how to do something like this:我阅读了文档,但没有意识到如何做这样的事情:

<some-tag>
   <star repeat={5} />
</some-tag>

I found only this ugly way:我发现只有这种丑陋的方式:

<some-tag>
   <star each={stars} />

   this.stars = new Array(5);
</some-tag>

After looking through the source, this might interest you.浏览源代码后, 可能会让您感兴趣。

If you plan on using the each attribute, you'll have to define some sort of an array for riot to pass to forEach .如果您计划使用each属性,则必须为 riot 定义某种数组以传递给forEach

This jsfiddle is another idea (that isn't optimal), but I think it illustrates the point. This jsfiddle是另一个想法(不是最优的),但我认为它说明了这一点。 Another solution is to use Riot's mixin system to build some sort of repeat attribute:另一种解决方案是使用 Riot 的mixin系统来构建某种repeat属性:

https://jsfiddle.net/aunn3gt0/2/ https://jsfiddle.net/aunn3gt0/2/

It's a great solution until you try using the <yield/> tag.在您尝试使用<yield/>标记之前,这是一个很好的解决方案。 Then it may need to be adjusted.那么它可能需要进行调整。 Here's how it works:它是这样工作的:

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()
      })
    })

  }
}

Then just attach it with this.mixin(repeat) and use it as you would expect:然后只需将它与this.mixin(repeat)附加并按您期望的方式使用它:

<tag repeat="10">Repeated 10 times.</tag>

Similar to what you've proposed, you can do this right in the template:与您提出的建议类似,您可以在模板中执行此操作:

<some-tag>
   <star each="{(NOTHING, i) in Array(state.repeatCount)}" />
</some-tag>

In this example, i contains the index.在此示例中, i包含索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM