簡單El-Table封裝(二)

自定義列內容 

Compoents文件夾下加個 VTable.vue 文件,內容如下

<template>
   <el-table :data="tableData" style="width: 100%">
     <!-- 添加索引 -->
     <el-table-column  type="index" width="55"></el-table-column>
     <!-- 添加一個複選框 -->
      <el-table-column checkbox v-if="checkbox" type="selection" width="55"></el-table-column>
      <template v-for="item in columns">
        <!--v-if 判斷類型 -->
        <el-table-column v-if="item.type === 'function'" :prop="item.prop" :label="item.label" :key="item.prop" >
          <!-- 套一層template,就是爲了取這一行的值-->
          <template slot-scope="scope">
              <!-- 這裏可以把數據傳給callback函數 -->
              <div v-html="item.callback && item.callback(scope.row)" ></div>
          </template>
        </el-table-column>
        <!-- 添加一個type標識用來標註類型的唯一性 -->
        <el-table-column v-else-if="item.type==='address'" :prop="item.prop" :label="item.label" :key="item.prop" >
          <template slot-scope="scope">
            <!-- 渲染有html標籤的 -->
            <div v-html="scope.row.address"></div>
          </template>
        </el-table-column>
        <el-table-column v-else :prop="item.prop" :label="item.label" :key="item.prop">
        </el-table-column>
      </template>

      
    </el-table>
</template>

<script>
export default {
    name:"VTable",
    props:{
      //接收列
      columns:{
        type:Array,
        default:()=>[]
      },
      //接收數據
      tableData:{
        type:Array,
        default:()=>[]
      },
      checkbox:Boolean
    },
    data() {
        return {
        }
      }
}
</script>
<style>
</style>

在home.vue頁面中使用


<template>
  <div class="home">
    <img alt="Vue logo" src="../assets/logo.png">
     <VTable checkbox :columns="columns" :tableData="tableData"></VTable>
  </div>
</template>

<script>
// @ is an alias to /src
import VTable from '@/components/VTable.vue'

export default {
  name: 'Home',
  data(){
    return{
      columns:[
          {
            type:'function',  //定義函數類型,用於回調
            label:"URL地址",
            prop:"date",
            callback:(val)=>{
              console.table(val);//通過回調把數據出過來,然後處理想要的格式
              return `<a href="http://www.baidu.com">${val.name}</a>`
            }},
          {label:"姓名",prop:"name"},
          {label:"地址",prop:"address",type:'address'},
          {label:"性別",prop:"gener"}
        ],
      tableData: [{
          date: '2016-05-02',
          name: '王小虎',
          address: '上海市普陀區金沙江路 <div style="color:red">1518</div> 弄',  //這裏有html標籤
          gener:"男"
        }, {
          date: '2016-05-04',
          name: '王小虎',
          address: '上海市普陀區金沙江路 1517 弄',
          gener:"女"
        }, {
          date: '2016-05-01',
          name: '王小虎',
          address: '上海市普陀區金沙江路 1519 弄'
        }, {
          date: '2016-05-03',
          name: '王小虎',
          address: '上海市普陀區金沙江路 1516 弄'
        }]
    }
  },
  components: {
     VTable
  }
}
</script>

效果圖

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章