[英]How to get first element displayed in dom-repeat?
我想在表格上显示dom-repeat的第一个元素。 其他应通过单击按钮添加。 在聚合物中如何可能出现这种情况。 如图所示。
如上图所示,默认情况下应显示room#1,单击按钮应从room#2开始添加。
码-
<form is="iron-form" id="form" method="post" action="/form/handler">
<template is='dom-repeat' items='{{ rooms }}'>
<div class="head">
<paper-item>
<div id="line"><span>Room# {{displayIndex(index)}}</span></div>
<template is='dom-if' if='{{displayIndex != 1}}'>
<paper-button toggles class=button on-click="deleteRoom"><img src="trash.png" height="20px" width="20px"></paper-button>
</template>
</paper-item>
</div>
<choice-form room="{{displayIndex(index)}}">{{ item.room }}</choice-form>
</template>
</form>
我将创建一个仅包含第一个房间(room#1)的新数组,然后单击按钮,将room#2添加到该数组中,然后在dom-repeat
而不是rooms
使用此数组。
您的示例在dom-if
包含一个绑定表达式(即if="{{displayIndex != 1}}"
),但是Polymer目前不支持该表达式。 您需要改用计算的绑定 / 属性 。
我假设rooms
最初包含一个项目,并且有一个按钮可以将更多项目添加到数组中。
该代码如下所示:
HTMLImports.whenReady(() => { Polymer({ is: 'x-foo', properties: { rooms: { type: Array, value: () => ['King'] }, _isDeleteHidden: { type: Boolean, computed: '_lte(rooms.length, 1)' } }, _lte(a, b) { return a <= b; }, _inc(index) { return index + 1; }, _deleteRoom(e) { this.splice('rooms', e.model.index, 1); }, _addRoom() { this.push('rooms', this._getRandomRoom()); }, _getRandomRoom() { const ROOMS = ['King', 'Queen', 'Double', 'Standard']; return ROOMS[randInt(0, ROOMS.length)] } }); }); function randInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min)) + min; }
<head> <base href="https://polygit.org/polymer+1.7.1/components/"> <script src="webcomponentsjs/webcomponents-lite.min.js"></script> <link rel="import" href="polymer/polymer.html"> <link rel="import" href="paper-button/paper-button.html"> <link rel="import" href="paper-item/paper-item.html"> <link rel="import" href="paper-icon-button/paper-icon-button.html"> <link rel="import" href="iron-icons/iron-icons.html"> </head> <body> <x-foo></x-foo> <dom-module id="x-foo"> <template> <paper-button on-tap="_addRoom">Add Room</paper-button> <template is="dom-repeat" items="[[rooms]]"> <paper-item> <span>Room #[[_inc(index)]] ([[item]])</span> <paper-icon-button hidden="[[_isDeleteHidden]]" icon="delete" on-tap="_deleteRoom"></paper-icon-button> </paper-item> </template> </template> </dom-module> </body>
我有自己的问题的答案。 您只需要在ready方法中调用一次add函数。 以下是代码。
ready: function () {
// For default first Room.
this.push('rooms', { room: "" });
this.roomCount = this.roomCount + 1;
},
addRoom: function () {
this.push('rooms', { room: "" });
this.roomCount = this.roomCount + 1;
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.