组件代码:
<template>
<div>
<el-table
ref="table"
:data="tableData"
:border="border"
v-bind="$attrs"
v-on="$listeners"
@selection-change="handleSelectionChange"
:cell-style="cellStyle"
:header-cell-style="headerStyle"
>
<el-table-column
v-if="shwoSelect"
type="selection"
width="55"
></el-table-column>
<el-table-column v-if="shwoIndex" type="index" width="50" label="序号">
</el-table-column>
<template v-for="(item, index) in columnList">
<el-table-column
v-if="!item.slot"
:key="index"
:prop="item.prop"
:label="item.label"
:width="item.width"
>
</el-table-column>
<el-table-column
v-if="item.slot"
:key="index"
:prop="item.prop"
:label="item.label"
:width="item.width"
>
<template v-slot="scope">
<span>
<slot :name="item.slot" :scope="scope" />
</span>
</template>
</el-table-column>
</template>
</el-table>
</div>
</template>
<script>
/**
* @module components/base/baseTable
* @desc 表格通用组件
* @vue-prop {Array} tableData - 表格数据
* @vue-prop {Array} columnList -表格label类数据
* 例 [ prop: 'demo',
label: 'demoLabel',
width: '180px', //制定列宽 默认自适应
slot: 'demo' //如需插入自定义内容,请使用插槽 如不需要使用插槽请删除这个参数
]
* @vue-prop {Boolean} shwoSelect -是否显示复选框
* @vue-prop {Boolean} shwoIndex -是否显示序号
* @vue-prop {Boolean} border -是否开启边框
* 父组件获取复选框选中的数组 :multipleSelection.sync="multipleSelection"
*/
export default {
name: 'baseTable',
props: {
tableData: {
type: Array,
default: () => []
},
columnList: {
type: Array,
default: () => []
},
shwoSelect: {
type: Boolean,
default: true
},
shwoIndex: {
type: Boolean,
default: true
},
border: {
type: Boolean,
default: true
}
},
data () {
return {
multipleSelection: [], // 选中的表格数据
cellStyle: { textAlign: 'center' },
headerStyle: {
background: '#f9f9f9',
textAlign: 'center'
}
}
},
methods: {
// 复选框的选中事件
handleSelectionChange (val) {
this.$emit('update:multipleSelection', val)
this.multipleSelection = val
}
},
watch: {
// 检查表格数据,滚动条回到顶部
tableData: function (val) {
this.$refs.table.bodyWrapper.scrollTop = 0
}
},
created () {},
mounted () {}
}
</script>
<style lang="scss" scoped></style>
页面引用组件方式:
<template>
<div class="home">
<!-- 使用插槽 -->
<baseTable
:multipleSelection.sync="multipleSelection"
:tableData="tableData"
:columnList="columnList"
>
<template v-slot:demo="{ scope }">
<!-- do something -->
{{ scope.row.demo }}
</template>
</baseTable>
<!-- 不使用插槽 -->
<baseTable
:multipleSelection.sync="multipleSelection"
:tableData="tableData"
:columnList="columnList"
>
</baseTable>
</div>
</template>
<script>
export default {
name: 'Home',
components: {},
data () {
return {
tableData: [
{
demo: '1'
}
],
columnList: [
{
prop: 'demo',
label: '地址',
width: '',
slot: 'demo' // 如不需要使用插槽请删除这个参数
}
],
multipleSelection: [] // 选中的表格数据
}
}
}
</script>