简体   繁体   中英

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

I need just repeat tag 5 times. 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 .

This jsfiddle is another idea (that isn't optimal), but I think it illustrates the point. Another solution is to use Riot's mixin system to build some sort of repeat attribute:

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

It's a great solution until you try using the <yield/> tag. 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:

<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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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