Vue的動態表格Demo


一、導入Vue的js(這一步就不演示了)

二、創建Vue的對象、並且添加測試數據

  注:el掛載的標簽ID,components的myTable表示的是,在頁面引入時的標簽,tabletest為綁定的模板ID(后面會添加),props作為一個數組類型,里面的參數為頁面引用時動態的參數(即為子組件傳數據所用)。

 1 <script type="text/javascript">
 2         var vue = new Vue({
 3             el: "#app",
 4             data: {
 5                 persons: [{"name": "張三","age": 19}, 
 6                           {"name": "張三","age": 20}, 
 7                           {"name": "張三","age": 21},
 8                           ],
 9                 person2:[{"name":"諸葛亮","age":1900,"birthday":"181年","sex":""},
10                 {"name":"貂蟬","age":1900,"birthday":"190年","sex":""},
11                 {"name":"劉備","age":1920,"birthday":"161年","sex":""},
12                 {"name":"周瑜","age":1930,"birthday":"161年","sex":""},
13                 ]
14             },
15             components: {
16                 myTable: {
17                     template: "#tabletest",
18                     props: ["persons"]
19                 }
20             }
21         })
22  </script>

三、創建一個Vue的模板

  注:template標簽下面有且只能有一個根標簽。第5行的v-for用於動態輸出列名、第7行循環每一個person對象、第9行輸出對象所有的值

 1 <template id="tabletest">
 2             <table>
 3                 <tr>
 4                     <td>num</td>
 5                     <td v-for="(value,key) in persons[0]">{{key}}</td>
 6                 </tr>
 7                 <tr v-for="(p,index) in persons">
 8                     <td>{{index+1}}</td>
 9                     <td v-for="value in p">{{value}}</td>
10                 </tr>
11             </table>
12  </template>

四、測試代碼

1 <div id="app">
2             <my-table :persons="persons"></my-table>
3             <my-table :persons="person2"></my-table>
4 </div>

注:表格的數據通過 :persons屬性 動態選擇(此屬性在components已經定義好)

五、整體代碼布局

 

 

 六、測試結果

  

 

 最后:有什么不對的地方,懇請各位斧正。謝謝!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM