[英]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.