使用Vue.js可以很方便的實現數據的綁定和更新,有時需要對一個一維數組進行分組以方便顯示,循環可以直接使用v-for,那分組呢?這里需要用到vue的computed特性,將數據動態計算分組。代碼如下
<!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> // 創建一個 Vue 實例或 "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個元素為一組來動態分組,在綁定數據的地方使用嵌套的v-for循環,結果如下圖(3列4行)
這里還對包裹數據的每個div的id作了特別的處理,動態產生id,每個id都有一個字符串前綴T,后面是數據的索引,索引采用i*3+j計算獲得,以便於對應到原始的數據list。
轉載請注明出處