自定義列的內容添加按鈕或自己想要的內容
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>
<el-table-column v-else-if="item.type === 'slot'" :prop="item.prop" :label="item.label" :key="item.prop" >
<!-- 套一層template,就是爲了取這一行的值-->
<template slot-scope="scope">
<!-- 定義插槽動態賦值個名字 -->
<slot :name="item.slot_name" :data_row="scope.row" ></slot>
</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">
<!-- 使用插槽 -->
<!-- v-slot:operation="slot22",這個slot22就是插槽中的數據-->
<template v-slot:operation="slot22">
<el-button type="primary" @click="jumn(slot22.data_row)" >編輯 </el-button>
</template>
</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"},
{type:'slot',label:"操作",prop:"operation",slot_name:'operation'}
],
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
},
methods:{
jumn(val){
console.log(val);
}
}
}
</script>