直接上代码了
// 自定义组件
<template>
<div class="x__table>
<el-table
v-loading="tableLoading"
:data="tableData"
border
stripe>
<el-table-column
v-if="index"
type="index"
label="序号"
align="center"
width="50">
<template slot-scope="scope">
<span>{{ scope.$index + (page.current - 1) * page.size + 1 }}</span>
</template>
</el-table-column>
<template v-for="(item, index) in tableOption">
<el-table-column
:key="index"
:prop="item.prop"
:label="item.label"
:align="item.align || 'center'"
:show-overflow-tooltip="item.overHidden || true">
<template slot-scope="scope">
// 这里通过插槽实现自定义列
<slot
v-if="item.slot"
:name="scope.column.property"
:row="scope.row"
:$index="scope.$index"
/>
<span v-else>{{ scope.row[scope.column.property] }}</span> // 这里的property自己打印出来看看就明白了
</template>
</el-table-column>
</template>
<el-table-column
label="操作"
align="center">
<template slot-scope="scope">
<slot
name="menu"
:row="scope.row"
:$index="scope.$index"
/>
</template>
</el-table-column>
</el-table>
<!-- 分页器 --> // 这里的分页器也是封装的一个组件,主要是和序号关联起来
<Pagination
v-show="page.total>0"
:total="page.total"
:page.sync="page.current"
:limit.sync="page.size"
@pagination="pageChange"
/>
</div>
</template>
<script>
import Pagination from '@/components/Pagination/index' // 有需要的下次再贴代码
export default {
name: 'XTable',
components: {
Pagination
},
props: {
index: {
type: Boolean,
default: function() {
return true
}
},
tableLoading: {
type: Boolean,
default: function() {
return false
}
},
tableData: {
type: Array,
default: function() {
return []
}
},
tableOption: {
type: Array,
default: function() {
return []
}
},
page: {
type: Object,
default: function() {
return {
total: 0,
current: 1,
page: 10
}
}
}
},
methods: {
pageChange() {
this.$emit('page-change')
}
}
}
</script>
组件使用方法:
<template>
<div>
<Xtable
:tableLoading="tableLoading"
:tableData="tableData"
:page="page"
:tableOption.sync="tableOption"
@page-change="getList">
<template
slot="hobby"
slot-scope="scope">
<el-tag>{{ scope.row.role }}</el-tag>
</template>
<template
slot="menu"
slot-scope="scope">
<el-button
type="text"
size="mini"
icon="el-icon-download"
@click="download(scope.row,scope.index)"
>下载
</el-button>
</template>
</Xtable>
</div>
</tempalte>
<script>
import Xtable from '@/components/Xtable/index'
export default {
components: {
Xtable
},
data() {
return {
tableLoading: false,
tableOption: [
{
label: '编号',
prop: 'id'
},
{
label: '姓名',
prop: 'name'
},
{
label: '年龄',
prop: 'name'
},
{
label: '爱好',
prop: 'hobby',
solt: true // 这里表示自定义列
}
],
tableData: [],
page: {
total: 0,
current: 1,
size: 10
},
searchForm: {}
},
create() {
this.getList()
},
methods: {
getList() {
// 获取数据
this.tableLoading = true
fetchList(
Object.assign({ currrent: this.page.current, size: this.page.size }, this.searchForm))
.then(res => {
this.tableData = res.data.records
this.total = res.data.total
this.tableLoading = false
})
.catch(() => {
this.tableLoading = false
})
}
}
</script>
基本上就是这个样子了,谢谢大家观看,有不对的地方多指教!
下回说下如何动态控制列的显隐