2017-06-12 144 views
-1

我正在尋找一個更好的優化解決方案,在聚合物2.0中有太多if。例如,我建立一個表格對象,其中每個單元格可以是文本,按鈕,鏈接,對象等。我希望用戶能夠輸入2D數組,並讓Polymer 2.0對象能夠選擇使用哪個標記。我目前的解決方案(下面)簡單地有幾個if語句,但這意味着每個單元格如果要調用每個語句。有沒有更好的方法來處理這個問題?聚合物2.0太多ifs

<template is="dom-if" if="[[matchCellType(cell, 'button')]]"> 
    <UI-Button id='[[cell.button.ID]]' class$='[[cell.button.class]]'>[[cell.button.text]]</UI-Button> 
</template> 
<template is="dom-if" if="[[matchCellType(cell, 'object')]]"> 
    <span class="object-toggle"></span>[[cell.title]] 
    <div class="properties"> 
     <template is="dom-repeat" items="[[getProps(cell)]]"> 
      <div class="properties_row"><div class="properties_cell"><b>[[item.title]]:</b></div><div style="display: table-cell">[[item.val]]</div></div> 
     </template> 
    </div> 
</template> 
<template is="dom-if" if="[[matchCellType(cell, 'link')]]"> 
    <a target="_blank" href='[[cell.link.href]]'>[[cell.link.text]]</a> 
</template> 
<template is="dom-if" if="[[matchCellType(cell, 'cell')]]"> 
    [[cell]] 
</template> 
<template is="dom-if" if="[[matchCellType(cell, 'textArea')]]"> 
    <ui-text-area rows="[[cell.textArea.rows]]" cols="[[cell.textArea.cols]]" id='[[cell.textArea.id]]' class$='[[cell.textArea.class]]' text= [[cell.textArea.text]]></ui-text-area> 
</template> 

回答

0

很多呼叫matchCellType的不傷害,如果它不是一個昂貴的計算(如果是這樣,你可以更新的財產,而不是在一個觀察者的屬性和測試)

因子出將一系列if組合成一個組件,所以你不會混亂你的表格

作爲使用dom-ifs的替代方法,計算單元格中的屬性或樣式類,始終呈現所有元素,並使用CSS僅具有匹配的元素是可見的。這將產生更多的DOM元素,但仍可能具有更好的性能,因爲瀏覽器處理hiddendisplay:none元素非常有效地

而不是幾個DOM-IFS衝壓,你可以創建和命令式地刪除節點

+0

感謝您的幫助! 我嘗試使用最初的行和單元的子組件,整個表看起來不對,這是我仍然計劃實施的一個好建議。 matchCellType是一組簡單的ifs。 渲染一切並隱藏它們是我不認爲我會想到的事情,這是一個整潔的想法。 我主要關心的是這種結構是緩慢而低效的。實際上,性能明智,它工作正常,即使是大數據集。我有點想添加更多,如果這個,但它似乎是一個不好的解決方案。 – mpavlis

+0

..有些人甚至做了<> – Markus