在寫商城項目時寫了一段垃圾代碼
根據methods返回值,來設置元素的行內樣式
//元素: <li> {{ shop.score[0].name }} <i :style="{ color: serviceScore(0) }">{{ shop.score[0].score }}</i> <i :style="{ backgroundColor: serviceScore(0) }">{{ score }}</i> </li> <li> {{ shop.score[1].name }} <i :style="{ color: serviceScore(1) }">{{ shop.score[1].score }}</i> <i :style="{ backgroundColor: serviceScore(1) }">{{ score }}</i> </li> //methods: serviceScore(i) { let scoreColor = null; if (this.shop.score[i].isBetter) { this.score = "高"; scoreColor = "red"; } else { this.score = "低"; scoreColor = "#6aa44a"; } return scoreColor; },
能正常顯示,但是console內出現Vue警告
測試下來,如果只有一個li,則不會warn,超過一個便會warn
給屬性綁定方法的話,Vue會認為你循環操作dom元素,即使你沒有循環,他也會發出警告(render - computed - render )
根據網上的說法,我以為是上面的問題,然后我采用笨方法,不使用methods,直接在style內使用三元返回結果,發現問題依舊存在。我把目光轉向了雙向綁定的score,將其去掉methods,warn消失
<li> {{ shop.score[0].name }} <i :style="{ color: serviceScore(0) }">{{ shop.score[0].score }}</i> <i :style="{ backgroundColor: serviceScore(0) }"> {{this.shop.score[0].isBetter ? "高" : "低"}} </i> </li> <li> {{ shop.score[1].name }} <i :style="{ color: serviceScore(1) }">{{ shop.score[1].score }}</i> <i :style="{ backgroundColor: serviceScore(1) }"> {{this.shop.score[1].isBetter ? "高" : "低"}} </i> </li>
解決方法:
循環一般用來讀取數據,而不要改變響應式數據。
根據這個思路,可以把methods或者computed計算完的數據放置於數組中,再在響應式內直接讀取數組元素