vue2 对vxe-table组件二次封装并全局引入
要求
新组件的写法要和旧组件保持一致,
那么保留原本的插槽,属性,方法
写法如下,以vxe-table为例
组件封装
<template>
<vxe-grid ref="vxeGrid" v-bind="$attrs" v-on="$listeners" @filter-change="filterChange">
<template v-for="slot in slots" #[slot]="data">
<slot :name="slot" v-bind="data"></slot>
</template>
<template #bottom v-if="filterTags.length">
<div class="filter-tags">
<transition-group class="transition">
<el-tag
v-for="tag in filterTags"
:key="tag.title"
closable
@close="filterClose(tag)"
>
{{ tag.title }}
</el-tag>
</transition-group>
<el-button
class="filter-tags-btn"
size="small"
icon="el-icon-delete"
@click="clearFilterGroup"
>清空</el-button
>
</div>
</template>
</vxe-grid>
</template>
js部分
<script>
export default {
name: 'YmsTable',
components: {},
data() {
return {
// 此处放置不定义在columns中的插槽枚举
staticSlots: ['form', 'toolbar', 'top', 'bottom', 'pager'],
filterTags: []
};
},
computed: {
slots() {
const columns = this.$attrs.columns;
// 获取定义在columns上的插槽
const extendSlot = [];
columns.forEach(col => {
if (col.slots) {
const slots = Object.values(col.slots);
extendSlot.push(...slots);
}
});
return [...this.staticSlots, ...extendSlot];
}
},
created() {},
mounted() {
this.initVxeMethod();
},
methods: {
// 暴露vxe-grid的方法
initVxeMethod() {
const vxeGrid = this.$refs.vxeGrid;
Object.entries(vxeGrid).forEach(e => {
const [key, value] = e;
if (typeof value === 'function') {
this[key] = this[key] || value;
}
});
},
// 筛选
filterChange({ filterList }) {
this.filterTags = [];
filterList.map(val => {
this.filterTags.push({
title: `${val.column.title}:${val.datas.join('')}`,
column: val.column
});
});
},
filterClose(tag) {
this.filterTags.splice(this.filterTags.indexOf(tag), 1);
this.$refs.vxeGrid.clearFilter(tag.column);
},
clearFilterGroup() {
if (this.$refs.vxeGrid.isFilter()) {
this.$refs.vxeGrid.clearFilter();
}
this.filterTags = [];
}
}
};
</script>
全局引入
在mian.js中
import Vue from 'vue';
import YmsTable from '@/component/ymsTable/index.vue';
Vue.component('YmsTable', YmsTable);
使用
和原本的写法保持一致
<yms-table
ref="vxeGrid"
:data="tableData"
v-bind="gridOptions"
:export-config="{}"
@cell-click="cellClick"
@sort-change="sortChange"
@filter-change="filterChange"
>
<template #pager>
<vxe-pager
:layouts="[
'Sizes',
'PrevJump',
'PrevPage',
'Number',
'NextPage',
'NextJump',
'FullJump',
'PageCount',
'Total'
]"
:current-page.sync="searchData.pageIndex"
:page-sizes="$FeePageSizes"
:page-size.sync="searchData.pageSize"
:total="searchData.total"
@page-change="handlePageChange"
>
</vxe-pager>
</template>
<template #operate="{ row }">
<div class="operate">
<button-group-custom
:btn-data="btnData1"
@btnClick1="editButton(row)"
></button-group-custom>
</div>
</template>
</yms-table>