RactiveJS-06 List sections

使用方法

使用{{#each list}}来对数组对象进行循环,看下面的例子:

<body>
    <div id="container"></div>
    <script type="text/ractive" id="template">
        <table>
            <tr>
                <th>姓名</th>
                <th>年龄</th>
                <th>能力</th>
            </tr>
            {{#each superHeroes}}
            <tr>
                <td>{{name}}</td>
                <td>{{age}}</td>
                <td>{{ability}}</td>
            </tr>
            {{/each}}
        </table>
    </script>
    <script>
        var xmen = [{name : "金刚狼", age : 23, ability : 'eat'},
                {name : "金刚狗", age : 32, ability : 'sleep'},
                {name : "金刚熊", age : 23, ability : 'run'}];
        var ractive1 = new Ractive({
          el : '#container',
          template : '#template',
          data : {
           superHeroes : xmen
          }
        });
        ractive1.set('superHeroes[0].name', '金刚猫')
    </script>
</body>

获得数组序号

Mustache并没能提供一个很好的方式获得数组序号,所以RactiveJS引入了序列变量(index reference)

{{#each list:num}}
  <!-- inside here, {{num}} is the index -->
{{/each}}

通过将num声明为序列变量,就可以像使用其他变量一样使用它。将上面的表格的循环数据改为:

<table>
   <tr>
        <th>序号</th>
        <th>姓名</th>
        <th>年龄</th>
        <th>能力</th>
    </tr>
    {{#each superHeroes:num}}
    <tr>
        <td>{{num+1}}</td>
        <td>{{name}}</td> 
        <td>{{age}}</td>
        <td>{{ability}}</td>
    </tr>
{{/each}}
</table>

这样就可以获得各组的序号。

增加数组项

可以使用ractive.update(‘list’)来更新表格数据。注意,如果没有给此方法传入变量,则它会更新所有元素。

也可以直接使用数组方法(push,pop,shift,unshift,splice,sort,reverse)方法自动更新数组。如果不想让上述方法自动更新数据,可以再初始化选项中设置了modifyArrays: false。

<script>
    var xmen = [{name : "金刚狼", age : 23, ability : 'eat'},
        {name : "金刚狗", age : 32, ability : 'sleep'},
        {name : "金刚熊", age : 23, ability : 'run'}];
    var ractive1 = new Ractive({
        el : '#container',
        template : '#template',
        data : {
            superHeroes : xmen
        }
    });
    xmen.push({name : "金刚兔", age : 123, ability : 'eat'});
    xmen.reverse();
    ractive1.update('superHeroes');
    //ractive1.reverse('superHeroes',{name : "金刚兔", age : 123, ability : 'eat'} );
    //ractive1.reverse('superHeroes');
</script>

排序

==后边排序的例子我并没有看懂,回头再说吧。==

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值