使用vue2的渲染函数封装elementui的表格

99 阅读1分钟

import { Table } from 'element-ui';

export default {
	name: 'AdminTable',
	props: Object.assign({}, Table.props, {
		columns: { type: Array, default: null },
		rowClass: { type: Function, default: null }
	}),
	data() {
		return {};
	},
	methods: {
		renderChildrenCols: function (h, column) {
			let this_ = this;
			let itemArr = [];
			column.children.forEach(function (item) {
				itemArr.push(this_.renderItem(h, item));
			});
			return h(
				'el-table-column',
				{
					props: column
				},
				itemArr
			);
		},

		renderItem: function (h, column) {
			return column.children ? this.renderChildrenCols(h, column) : this.renderColsItem(h, column);
		},
		renderColsItem: function (h, item) {
			let customSlot = this.$scopedSlots[item.customSlot]; // 自定义插槽
			return h('el-table-column', {
				props: item,
				// 动态插槽
				scopedSlots: customSlot
					? {
							default: props => customSlot({ ...props, colItem: item })
					  }
					: {}
			});
		},

		// 渲染表格
		renderTable: function (h, colsTree) {
			let this_ = this;
			let arr = [];
			colsTree.forEach(function (item, i) {
				arr.push(this_.renderItem(h, item, '0', i));
			});
			return arr;
		}
	},
	render(createElement) {
		// console.log('this.$props', this.$props);
		return createElement(
			Table,
			{
				props: {
					...this.$props
				},
				ref: 'elementRef',
				style: {
					width: '100%'
				},
				class: 'admin-table-ui',
				on: {
					// 各种方法自行添加
					'selection-change': selection => {
						this.$emit('selection-change', selection);
					},
					select: (selection, row) => {
						this.$emit('select', selection, row);
					},
					'expand-change': (row, expanded) => {
						this.$emit('expand-change', row, expanded);
					}
				}
			},
			this.renderTable(createElement, this.columns)
		);
	}
};