Polymer2.0通過資料繫結更改元素樣式
阿新 • • 發佈:2018-12-10
<link rel="import" href="../bower_components/polymer/polymer-element.html"> <link rel="import" href="../bower_components/polymer/lib/elements/dom-repeat.html"> <dom-module id="my-element"> <template> <div on-click="changeBgColor"> <dom-repeat items="[[data]]"> <template> <div index$="[[index]]" style$="background: [[item.background]]; width:200px; height:200px; border:1px solid gray;">[[item.background]]</div> </template> </dom-repeat> </div> </template> <script> class MyElement extends Polymer.Element{ static get is () { return "my-element"; } static get properties(){ return{ data: { type: Array, value: [ {background: '#00ff00'}, {background: '#00ff00'}, {background: '#00ff00'} ], reflectToAttribute: true } } } changeBgColor(e){ let index = e.target.getAttribute('index'); if(index !== undefined){ let arr = []; this.data.forEach( (v, i) => { if(i == index) arr.push({background: "#ff0000"}); else arr.push({background: "#00ff00"}); }); this.data = arr; }else{ return; } } } customElements.define( MyElement.is, MyElement); </script> </dom-module> <my-element></my-element>