使用Vue.js可以很方便的實(shí)現(xiàn)數(shù)據(jù)的綁定和更新,有時需要對一個一維數(shù)組進(jìn)行分組以方便顯示,循環(huán)可以直接使用v-for,那分組呢?這里需要用到vue的computed特性,將數(shù)據(jù)動態(tài)計算分組。
代碼如下:
<!DOCTYPE html><html><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <meta charset="utf-8" /> <script src="Scripts/vue.js"></script></head><body> <!--這是我們的View--> <div id="app"> <table> <tbody> <tr v-for="(row,i) in listTemp"> <td v-for="(cell,j) in row"> <div :id="'T_'+(i*3+j)">Data-{{cell}}</div> </td> </tr> </tbody> </table> </div></body></html><script src="Scripts/vue.js"></script><script> // 創(chuàng)建一個 Vue 實(shí)例或 "ViewModel" // 它連接 View 與 Model new Vue({ el: '#app', data: { list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] }, computed: { listTemp: function () { var list = this.list; var arrTemp = []; var index = 0; var sectionCount = 3; for (var i = 0; i < list.length; i++) { index = parseInt(i / sectionCount); if (arrTemp.length <= index) { arrTemp.push([]); } arrTemp[index].push(list[i]); } return arrTemp; } }, })</script>
在computed中以3個元素為一組來動態(tài)分組,在綁定數(shù)據(jù)的地方使用嵌套的v-for循環(huán),結(jié)果如下圖(3列4行)
這里還對包裹數(shù)據(jù)的每個div的id作了特別的處理,動態(tài)產(chǎn)生id,每個id都有一個字符串前綴T,后面是數(shù)據(jù)的索引,索引采用i*3+j計算獲得,以便于對應(yīng)到原始的數(shù)據(jù)list。
以上這篇Vue中v-for的數(shù)據(jù)分組實(shí)例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答