前些天發現了一個巨牛的人工智能學習網站,通俗易懂,風趣幽默,忍不住分享一下給大家。點擊跳轉到教程。
1.需求:
我想要一個 table 組件能在實際調用時動態生成所有的? tr 、td 。
后端返回的只是一個 list , 前端頁面解析時只要把這個 list 作為參數傳給 這個組件就能自動展示任意一維數組的所有數據。
2. 實現:
定義一個組件,取名為 oneTable,用雙重 for 實現需求。
oneTable :
<template><div><table class="table table-hover"><thead><tr><!-- 循環出表頭,用英文的逗號拆分字串 --><th v-for="(item,index) in headerList.split(',')" :key="index">{{item}}</th></tr></thead><tbody><!-- 循環出有多少行數據,即 list 中有多少條數據,得到 list 中的每個元素 --><tr v-for="(item,index) in bodyInfoList" :key="index"><!-- 循環取到元素的每個屬性,并展示 --><td v-for="(val,index) in item" :key="index">{{val}}</td></tr></tbody></table></div>
</template><script>
export default {name: "one",props: {headerList: {type: String, // 亦可接收 Object 類型參數default: "headerList"},bodyInfoList: {type: Array,default: "bodyInfoList"}}
};
</script>
父級組件調用處:
父級組件代碼:(目前用的是假數據,請求后端接口獲取 list 尚有待完善)
<template><div><oneTable :headerList="headerList" :bodyInfoList="bodyInfoList"></oneTable></div>
</template><script>
import oneTable from "../parts/oneTable";export default {name: "myCare",data() {return {headerList: "賬號,昵稱,角色,性別,生日,地區", // 注意:逗號是英文的逗號bodyInfoList: [{account: "admin",role_name: "全局管理員",nickname: "小熊",gentle: "男",birthday: "2019-01-02",region: "成都"},{account: "jiang",role_name: "系統管理員",nickname: "暮色",gentle: "女",birthday: "2012-12-28",region: "廣州"}]};},components: {oneTable},methods: {createdFun() {},mountedFun() {this.$ajax.get(this.GLOBAL.BASE_URL + "/gentle/first").then(res => {// data = res.data;console.log(res.data.navList);});}},// 頁面加載就執行created() {},// 頁面加載完成后執行mounted() {this.mountedFun();}
};
</script>
3.運行效果: