概述
1.一般封装的组件都有需要,点击内部按钮或者什么,带着数据触发父组件方法的情况,
这时可能会想到$emit子传父,但是其实我用过这种方式,少还好,一但函数多了,
那组件身上一堆@函数,看的很难看,又多,但又没办法,毕竟必须要每个都写@函数
今天在公司看到了另一种封装方法,我觉得可以借鉴一下,很不错
就传一个对象给子组件,里面传相应的配置,比如一个按钮对象数组,
每个对象身上有按钮类型,触发的父函数名等等,还可以传很多东西,
可以放在当前目录的mock.js里,这里主要讲讲这个触发的父函数名
传进去之后,会在相关按钮上绑定同一个的函数,
比如叫triggerMethods(funcName,data),不同的按钮传接收到得不同得函数名,
以及各自的数据然后函数里通过this.$parent[funcName](data)触发函数
很妙啊,很方便 这样不管多少个方法,子组件上也只会看到传的一个数据对象而已
2.template上居然可以v-for,一直以为不可以
二次封装el-table 封装的datatable
<template>
<div class="data_table_wrap" id="mone_test_data_table">
<!-- 条件过滤表单 -->
<slot v-if="tableCfg.filterSlot" name="tableFilterSlot"></slot>
<div v-else-if="!tableCfg.filterSlot && hasFilter" class="table_filter_form_wrap">
<el-row class="title">
<el-col :span="12">
<i class="el-icon-search"></i>筛选查询
</el-col>
<el-col :span="12" class="t_r">
<el-button type="primary" size="mini">查询</el-button>
<el-button type="primary" size="mini">重置</el-button>
</el-col>
</el-row>
<el-form :model="filterForm" class="filter_form" size="small" label-width="100px;">
<el-row>
<el-col :span="8" v-for="item in filterCfg" :key="item.name">
<el-form-item :label="item.label" :prop="item.name">
<el-input v-if="item.type == 'text'" v-model="filterForm[item.name]" :placeholder="item.label"></el-input>
<el-select v-if="item.type == 'select'" v-model="filterForm[item.name]" :placeholder="item.label">
<el-option v-for="(o, i) in item.option" :key="o.value + i" :label="o.label" :value="o.value"></el-option>
</el-select>
</el-form-item>
</el-col>
</el-row>
</el-form>
</div>
<!-- 表格工具栏 -->
<slot v-if="tableCfg.toolbarSlot && tableCfg.showToolbar" name="tableToolbarSlot"></slot>
<el-row v-else-if="!tableCfg.toolbarSlot && tableCfg.showToolbar" class="toolbar_wrap not_filter_toolbar_wrap">
<el-col :span="20" >
<div class="toolbar_btn_wrap" v-show="!isShowBatchOperationBtn">
<template v-if="hasToolbarBtn">
<label v-for="item in toolbarCfg.btn" :key="item.id">
<el-button v-if="item.type == 'primary'" @click="triggerParentMethod(item.clickEvent, { currBtnConfig: item})" type="primary" size="mini" class="toolbar_btn">{{ item.label }}</el-button>
<el-button v-else-if="item.type == 'danger'" @click="triggerParentMethod(item.clickEvent, { currBtnConfig: item})" type="danger" size="mini" class="toolbar_btn">{{ item.label }}</el-button>
<div v-else-if="item.type == 'dropdown'" class="toolbar_btn_dropdown">
<span>{{ item.label }} </span> <i class="el-icon-caret-bottom"></i>
<ul>
<li v-for="menu in item.dropdownMenu" :key="menu.id" @click="handleCommand(menu)">{{ menu.label }}</li>
</ul>
</div>
<el-button v-else @click="triggerParentMethod(item.clickEvent, { currBtnConfig: item})" type="text" size="mini" class="toolbar_btn">{{ item.label }}</el-button>
</label>
</template>
<span v-if="hasToolbarBatchOperationBtn" class="toolbar_btn toolbar_btn_batch_operation" @click="changeBatchOperationState(true)"><i class="icon iconfont icon-bianji1"></i>批量操作</span>
</div>
<label class="batch_operation_wrap" v-show="isShowBatchOperationBtn" v-if="hasToolbarBatchOperationBtn">
<span @click="changeBatchOperationState(false)" class="mone_test_btn_text"><i class="el-icon-refresh-left"></i>取消</span>
<span v-for="item in toolbarCfg.batchOperationBtn" :key="item.id" class="mone_test_btn_text"
@click="triggerParentMethod(item.clickEvent, { currBtnConfig: item, isBatchOperation: true})"
>
{{ item.label }}
</span>
</label>
</el-col>
<el-col :span="4" class="t_r">
<el-dropdown class="toolbar_btn" trigger="click">
<span class="el-dropdown-link btn_set_column_state">
<i class="el-icon-setting"></i>
</span>
<el-dropdown-menu slot="dropdown" class="column_state_list_wrap mone_test_dataTableColumnStateList">
<ul class="column_state_list_title">
<li class="">
<el-checkbox :indeterminate="columnStateCfg.indeterminate" v-model="columnStateCfg.checkAll" @change="columnStateClickAll">列表项</el-checkbox>
</li>
</ul>
<el-checkbox-group v-model="columnStateCfg.showColumn" @change="columnStateChange">
<ul>
<li v-for="(item, i) in theadCfg" :key="i">
<el-checkbox :label="item.prop">
<span>{{ item.label }}</span>
</el-checkbox>
</li>
</ul>
</el-checkbox-group>
</el-dropdown-menu>
</el-dropdown>
</el-col>
</el-row>
<!-- 表格 -->
<el-table :data="data" @selection-change="handleSelectionChange" class="data_table" border>
<el-table-column type="selection" width="55"></el-table-column>
<template v-for="(item, index) in theadCfg">
<template v-if="!item.isHide">
<!-- 链接 -->
<el-table-column v-if="item.type=='link'" :prop="item.prop" :label="item.label" :width="item.width" :key="item.prop+index"
:render-header="(h,obj) => rendThFilter(h, Object.assign(obj, {cfg: item}))"
>
<template slot-scope="scope">
<span v-if="!item.switch" class="mone_test_btn_text extended_display link" @click="triggerParentMethod(item.clickEvent, {index: scope.$index, row: scope.row, columnConfig: item})"> {{ scope.row[item.prop] }} </span>
<!--<el-button v-if="!item.switch" size="mini" type="text">{{ scope.row[item.prop] }}</el-button>-->
<span v-if="item.switch" class="link"
:style="{color: getColor(scope.row[item.prop], 'color', item) }"
@click="triggerParentMethod(item.clickEvent, {index: scope.$index, row: scope.row, columnConfig: item})"
>
{{ scope.row[item.prop] }}
</span>
<!--<slot name="testSlot">myslot</slot>-->
</template>
</el-table-column>
<!-- -->
<!--:filters="item.filter" :filter-method="filterThead" :filtered-value="['HTTP']"-->
<el-table-column v-else-if="item.type=='tagRound'" :prop="item.prop" :label="item.label" :width="item.width" :key="item.prop+index"
:render-header="(h,obj) => rendThFilter(h, Object.assign(obj, {cfg: item}))"
>
<template slot-scope="scope">
<span class="tag_Round" :style="{
color: getColor(scope.row[item.prop], 'color', item),
'background-color': getColor(scope.row[item.prop], 'bgColor', item),
'border-color': getColor(scope.row[item.prop], 'borderColor', item),
}"
>
{{ scope.row[item.prop] }}
</span>
</template>
</el-table-column>
<!-- -->
<el-table-column v-else-if="item.type=='tag'" :prop="item.prop" :label="item.label" :width="item.width" :key="item.prop+index"
:render-header="(h,obj) => rendThFilter(h, Object.assign(obj, {cfg: item}))"
>
<template slot-scope="scope">
<span class="tag" :style="{
color: getColor(scope.row[item.prop], 'color', item),
'background-color': getColor(scope.row[item.prop], 'bgColor', item),
'border-color': getColor(scope.row[item.prop], 'borderColor', item),
}"
>
{{ scope.row[item.prop] }}
</span>
</template>
</el-table-column>
<!-- 操作列 -->
<el-table-column v-else-if="item.type=='operation'" :label="item.label" :width="item.width" :key="item.prop+index"
:render-header="(h,obj) => rendThFilter(h, Object.assign(obj, {cfg: item}))"
>
<template slot-scope="scope">
<el-tooltip effect="dark" :content="oBtn.tooltip || oBtn.label" placement="top" v-for="oBtn in item.btns" :key="oBtn.id" popper-class="mone_test_dataTableOperateBtnTip">
<span @click="triggerParentMethod(oBtn.clickEvent, {index: scope.$index, row: scope.row, columnConfig: item, currBtnConfig: oBtn })" class="mone_test_btn_text operation_btn">
<i :class="oBtn.icon"></i>{{ oBtn.label }}
</span>
</el-tooltip>
</template>
</el-table-column>
<!-- 插槽 -->
<el-table-column v-else-if="item.type=='slot'" :prop="item.prop" :label="item.label" :width="item.width" :key="item.prop+index"
:render-header="(h,obj) => rendThFilter(h, Object.assign(obj, {cfg: item}))"
>
<template slot-scope="scope">
<slot name="customColumn" :row="{...scope.row}" :index="scope.$index" :colCfg="{...item}"></slot>
<!--<slot name="customColumn" :data="{...scope}"></slot>-->
</template>
<!--<slot :data="{...scope}"></slot>-->
</el-table-column>
<!-- 默认 -->
<el-table-column v-else :prop="item.prop" :label="item.label" :width="item.width" :key="item.prop+index"
:render-header="(h,obj) => rendThFilter(h, Object.assign(obj, {cfg: item}))"
></el-table-column>
</template>
</template>
</el-table>
<div v-if="tableCfg.showPagination" v-show="data&&data.length>0" class="pagination_wrap">
<el-pagination ref="pagination" :current-page="pagination.pageNum" background
:page-sizes="pagination.pageSizes"
:page-size="pagination.pageSize"
:layout="pagination.layout"
:total="pagination.total"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
></el-pagination>
</div>
</div>
</template>
<script lang="ts">
import { Component, Vue, Prop, Watch} from 'vue-property-decorator';
// import { ElForm } from 'element-ui/types/form.js'
import { DefaultCfg, TableCfg } from './mocks'
import { DataTableService } from 'mone-test/services';
import _ from 'lodash';
import ThFilter from './thFilter.vue'
const DefaultPagination = {
pageNum: 1,
pageSizes: [10, 20, 30, 50],
pageSize: 10,
total: 0,
layout: 'total, sizes, prev, pager, next, jumper'
};
@Component({
name: 'DataTable',
components: {
}
})
export default class DataTable extends Vue {
/*** props ***/
@Prop({ type: Object, default: ()=>{ return {}; } }) configInfo;
@Prop({ type: Array, default: ()=>{ return []; } }) tableData;
/*** data ***/
tableCfg: object = {};
data: any = []; // 表格数据
filterCfg: object = []; // 筛选查询的配置
filterForm: object = {}; // 筛选查询的表单
isShowBatchOperationBtn = false;
toolbarCfg: object = {};
theadCfg: object = []; // 表头配置
columnStateCfg: object = { // 列显示隐藏相关
indeterminate: false,
checkAll: true,
showColumn: [], // 显示的列的
}; // 显示隐藏列的相关配置
pagination: object = {}; // 分页的相关配置
requestCfg: object = {}; // 请求配置
hasFilter: boolean = false; // 是否有筛选过滤
hasToolbarBtn: boolean = false; // 是否有工具按钮
hasToolbarBatchOperationBtn: boolean = false; // 是否有批量操作按钮
getDataThFilterParam: object = {}; // 查询数据的表头筛选参数
selectedData: object[] = [];
/*** computed ***/
/*** watch ***/
@Watch('configInfo', {deep: true})
getConfigInfo(newVal: string, oldVal: string){
this.initData();
this.getTableData();
}
constructor() {
super()
}
created(){
this.initData();
this.getTableData();
}
/*** methods ***/
// 初始化数据
initData(){
const self = this as any;
// Object.assign(self.configInfo, DefaultCfg);
self.tableCfg = _.extend({}, DefaultCfg, self.configInfo);
// Object.assign(self.treeConfig, self.configInfo);
// 筛选
if(self.tableCfg.filter && self.tableCfg.filter.length){
self.filterCfg = _.extend([], self.tableCfg.filter);
self.filterForm = {};
self.tableCfg.filter.forEach(item => {
self.$set(self.filterForm, item.name, '');
});
self.hasFilter = true;
}
// toolbar
if(self.tableCfg.toolbars && Object.keys(self.tableCfg.toolbars).length){
self.toolbarCfg = _.extend({}, self.tableCfg.toolbars);
self.hasToolbarBtn = self.toolbarCfg.btn && self.toolbarCfg.btn.length ? true : false;
self.hasToolbarBatchOperationBtn = self.toolbarCfg.batchOperationBtn && self.toolbarCfg.batchOperationBtn.length ? true : false;
}
// 表头配置
if(self.tableCfg.thead && self.tableCfg.thead.length){
self.theadCfg = _.extend([], self.tableCfg.thead);
// 表头筛选
self.tableCfg.thead.forEach(item => {
if(!!item.filterDefaultValue){
self.$set(self.getDataThFilterParam, item.prop, item.filterDefaultValue);
}
});
}
// 显示隐藏列的相关配置
const showColumn: any[] = [];
self.theadCfg.forEach(item => {
if(!item.isHide){
showColumn.push(item.prop);
}
});
self.$set(self.columnStateCfg, 'showColumn', showColumn);
// 分页
self.pagination = _.extend({}, (self.tableCfg as any).pagination);
// 请求配置
self.requestCfg = _.extend({}, (self.tableCfg as any).request);
}
//
handleCommand(command) {
if(!command.clickEvent || command.clickEvent == '') return false;
this.$parent[command.clickEvent]();
}
// 切换显示 批量操作 按钮状态
changeBatchOperationState(state){
this.isShowBatchOperationBtn = state;
}
// 设置列显示隐藏状态
theadStateChange(item, isChecked, childrenChecked){
console.log(item);
console.log(isChecked);
console.log(childrenChecked);
}
// 点击 列显示/隐藏 全选
columnStateClickAll(val){
console.log(val);
const self = this as any;
self.$set(self.columnStateCfg, 'showColumn', val ? _.map(self.theadCfg, _.iteratee('prop')) : []);
self.$set(self.columnStateCfg, 'indeterminate', false);
self.theadCfg.forEach(item => {
self.$set(item, 'isHide', !val);
});
}
// 点击 列显示/隐藏
columnStateChange(val){
console.log(val);
const self = this as any;
const checkedCount: number = val.length;
self.$set(self.columnStateCfg, 'checkAll', checkedCount === self.theadCfg.length);
self.$set(self.columnStateCfg, 'indeterminate', checkedCount > 0 && checkedCount < self.theadCfg.length);
const changeState = {};
val.forEach(checked => {
changeState[checked] = true;
});
self.theadCfg.forEach(item => {
self.$set(item, 'isHide', !changeState[item.prop]);
});
}
//
handleSelectionChange(val){
this.selectedData = val;
}
// 触发父级方法
triggerParentMethod(FunName, data){
const self = this;
if(!FunName || FunName == ''){
return false;
}
// 批量操作
if(data.isBatchOperation){
self.$set(data, 'selectedData', self.selectedData)
}
if(data.currBtnConfig && data.currBtnConfig.id=='delete'){
if(!data.selectedData && data.row){
self.$set(data, 'selectedData', [data.row]);
}
self.delConfirm(FunName, data);
}else{
self.$parent[FunName](data);
}
}
// 获取颜色
getColor(val, colorKey, cfg){
let color = '';
const condition = _.get(cfg, 'switch', {});
// 没有配置 switch 时 返回空字符串
if(_.isEmpty(condition)){
return '';
}
if (condition[val]){
if (typeof condition[val] === "object" && condition[val][colorKey]){
color = condition[val][colorKey];
}
}else if(condition.default){
if (typeof condition.default === "object" && condition.default[colorKey]) {
color = condition.default[colorKey];
} else {
color = condition.default;
}
}else{
return '';
}
return color;
}
// 切换每页显示数量
handleSizeChange(val) {
const self = this as any;
self.$set(self.pagination, 'pageNum', 1);
self.$set(self.pagination, 'pageSize', val);
self.getTableData();
}
// 翻页
handleCurrentChange(val) {
const self = this as any;
self.$set(self.pagination, 'pageNum', val);
self.getTableData();
}
// 获取表格数据
getTableData(){
const self = this as any;
if(!self.requestCfg.url || self.requestCfg.url==''){
self.data = self.tableData;
return false;
}
let params = Object.assign({}, self.getDataThFilterParam, self.requestCfg.params);
let header = self.requestCfg.header;
if((self.tableCfg as any).pagination){
Object.assign(params, {
pageNum: self.pagination.pageNum,
pageSize: self.pagination.pageSize
});
}
DataTableService.getTableData(self.requestCfg.url, params).then(res => {
if(res.code == 200){
self.data = res.data;
self.$set(self.pagination, 'total', res.pageParam.total);
}else{
this.$message.error(res.message);
}
if(self.requestCfg.callback || self.requestCfg.callback!=''){
self.triggerParentMethod(self.requestCfg.callback, res)
}
}).finally(() => {
});
// self.$http.get('./data/knowledge.json').then(res => {
// let d = res.data;
// self.datas = d;
// }).catch(err => {
// console.log(err);
// });
}
// 表头过滤
filterThead1(value, row){
return row.tag === value;
}
// 渲染表头
rendThFilter(createElement, { column, $index, cfg }){
const self = this as any;
if(!cfg.filterTyle || cfg.filterTyle==''){
return createElement('div', {style: 'display: flex;'}, [
createElement('div', {
domProps: {
innerHTML: column.label
}
}),
]);
}
return createElement('div', {style: 'display: flex;'}, [
createElement('div', {
domProps: {
innerHTML: column.label
}
}),
createElement(ThFilter, {
style: 'cursor: pointer;',
props: {
type: cfg.filterTyle || '',
options: cfg.filter || [],
defaultValue: cfg.filterDefaultValue, // 默认值
defaultProps: cfg.filterProp || { value: 'value', text: 'text' },
column: column,
columnCfg: cfg,
},
on: {
filterThead: self.filterThead
},
nativeOn: {},
})
])
}
// 表头过滤
filterThead({filterType, value, columnCfg}){
const self = this as any;
self.$set(self.getDataThFilterParam, columnCfg['prop'], value);
self.getTableData();
}
// 删除提示
delConfirm(FunName, data){
const self = this as any;
if(!data.selectedData.length){
self.$message({ type: 'warning', message: '请选择要操作的数据' });
return false;
}
let msg = self.configInfo.deleteTipText ? self.configInfo.deleteTipText : '确定删除吗?';
this.$confirm(msg, '提示', {
cancelButtonText: '取消',
confirmButtonText: '确定',
type: 'warning'
}).then(() => {
self.$parent[FunName](data);
}).catch(() => {
self.$message({ type: 'info', message: '已取消删除' });
});
}
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
#mone_test_data_table{
background-color: #fff;
.table_filter_form_wrap{
.title{
background-color: #F3F3F3; padding: 6px 10px; line-height: 28px;
}
.filter_form{
padding: 10px;
}
::v-deep .el-form-item__content{
display: inline-block;
}
}
.toolbar_wrap{
background-color: #F3F3F3; height: 50px; line-height: 50px; padding: 0px 10px;
.toolbar_btn_wrap{
display: inline-block;
}
.toolbar_btn{
margin: 0 10px; cursor: pointer;
}
.toolbar_btn_dropdown{
margin: 0 10px; display: inline-block; position: relative; cursor: pointer;
background-color: #0eafc0; color: #fff; line-height: 1em; padding: 7px 0 7px 0;
span{
padding: 0 10px 0 20px;
}
i{
padding: 0 10px;
}
&:before{
content: ""; position: absolute; right: 30px; top: 0; width: 1px; height: 100%; background-color: #fff;
}
ul{
display: none;
position: absolute; z-index: 99; background-color: #fff; border: 1px solid #ccc;
width: 100%; left: 0; top: 28px; color: #7E7E7E;
text-align: center;
}
li{
padding: 5px 10px; border-bottom: 1px dashed #ccc;
&:hover{
color: #348FE4; background-color: #ECF5FF;
}
}
&:hover ul{
display: block;
}
}
.toolbar_btn_batch_operation{
&:hover{
color: #348FE4;
}
i{
font-size: 18px; margin-right: 2px;
}
}
.batch_operation_wrap span{
margin: 0 10px;
&:not(:first-child):before{
content: ""; width: 1px; height: 1em; background-color: #333;
position: absolute; left: -10px; top: 19px;
}
}
.batch_operation_wrap i{
font-size: 16px; margin-right: 5px;
}
::v-deep .el-button-group .el-button{
height: auto;
}
::v-deep .el-button--primary{
background-color: #0EAFC0; border-color: #0EAFC0;
}
.el-button--text:focus, .el-button--text:hover{
color: #3a8ee6;
}
.el-button--text{
color: #333;
}
/*.el-button--primary:focus, .el-button--primary:hover{}*/
.btn_set_column_state{
font-size: 20px;
}
}
.not_filter_toolbar_wrap{
background-color: #fff; border: 1px solid #EBEEF5;
}
.data_table{
width: 100%; font-size: 12px;
.tag_Round{
display: inline-block; color: #333; border-radius: 22px; height: 22px; font-size: 12px; padding: 1px 10px;
}
.tag {
display: inline-block; color: #333; font-size: 12px; padding: 1px 10px; border-radius: 4px;
border-width: 1px; border-style: solid; border-color: inherit;
}
.link{
cursor: pointer; overflow: hidden; white-space: nowrap; display: block;
&:hover{
text-decoration: underline;
}
}
.operation_btn{
margin-left: 5px; font-size: 16px;
}
::v-deep th{
background-color: #f2eded; position: relative;
}
}
::v-deep .el-table--medium td{
padding: 2px 0;
}
::v-deep .el-table .cell{
white-space: nowrap;
}
.pagination_wrap{
padding: 10px 0px; text-align: right;
}
.el-button--primary{
background-color: #0EAFC0; border-color: #0EAFC0;
}
}
.t_c{ text-align: center; }
.t_r{ text-align: right; }
.mone_test_dataTableColumnStateList{
padding: 0px; border: 1px solid #D7D7D7; margin-top: 0px;
min-width: 150px; max-width: 500px;
&:before{
content: ""; width: 1px; height: 100%; background-color: #D7D7D7;
position: absolute; left: 36px; top: 0;
}
.column_state_list_title{
padding: 4px 10px;
border-bottom: 1px solid #D7D7D7;
background-color: #F2F2F2;
::v-deep .el-checkbox__label{
font-weight: bold;
}
}
.el-checkbox-group li{
padding: 4px 10px;
border-bottom: 1px solid #D7D7D7;
}
.el-checkbox{
line-height: 1em;
}
::v-deep .el-checkbox__label{
margin-left: 20px;
}
::v-deep .popper__arrow{
border-bottom-color: #D7D7D7;
}
.el-tree{
border-top: 1px solid #D7D7D7;
}
::v-deep .el-tree-node{
padding-right: 20px;
padding-top: 5px;
padding-bottom: 5px;
border-bottom: 1px solid #D7D7D7;
}
::v-deep .el-checkbox__input.is-checked+.el-checkbox__label{
color: #333;
}
}
</style>
<style>
.mone_test_dataTableOperateBtnTip{
padding: 5px; font-size: 12px;
}
</style>
最后
以上就是陶醉皮带为你收集整理的关于封装组件的一些思路--持续更新的全部内容,希望文章能够帮你解决关于封装组件的一些思路--持续更新所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复