简体   繁体   中英

How do we detect the end of a loop/render in Riot.js?

In Riot.js, it is possible conditionally display an element using and if attribute/helper. https://muut.com/riotjs/guide/#conditionals

I have been trying hard to get this right, and it does not seem to work for me. Here is a Codepen. http://codepen.io/geordee/pen/EjYgPq?editors=100

<!-- include riot.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/riot/2.0.14/riot+compiler.min.js"></script>

<script type="riot/tag">
  <todo-item>
    <li>
      { item }
    </li>
  </todo-item>
</script>

<!-- include the tag -->
<script type="riot/tag">
  <todo>
    <h3>{ opts.title }</h3>
    <p>total items: { opts.items.length }</p>
    <ul each={ item, i in opts.items }>
      <todo-item item={ item }></todo-item>

      <!-- these work -->
      <div if={ true }> item { i } </div>
      <div if={ false }> do not show this </div>

      <!-- conditional -->
      <div if={ i == (opts.items.length - 1) }>
        last item conditional
      </div>
      <!-- ternary -->
      <div if={ i == opts.items.length - 1 ? true : false }>
        last item ternary
      </div>
      <!-- variable -->
      <div if={ is_true }>
        last item variable
      </div>
      <!-- function -->
      <div if={ end_of_list(opts.items, i) }>
        last item function
      </div>
    </ul>

    <style scoped>
      :scope { display: block }
      h3 { font-size: 120% }
    </style>

    this.is_true = true;

    this.end_of_list = function (items, i) {
      return ( i == items.length - 1 );
    }
  </todo>
</script>

<!-- mount point -->
<todo></todo>

<!-- mount the tag -->
<script>
  riot.mount('todo', { title: 'My Todo', items: [ 'buy milk', 'send letter' ] });
</script>

You have to use parent inside of the loop as the scope has changed.

https://muut.com/riotjs/guide/#context

In the looped element everything but the each attribute belongs to the child context, so the title can be accessed directly and remove needs to be prefixed with parent. since the method is not a property of the looped item.

So the following will work:

<div if={ ((parent.opts.items.length-1) == i) }>Hello :)</div>

http://codepen.io/anon/pen/KpPgLj?editors=100

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