难点:如何在不定义两个表头的情况下,保证每次传入父组件的参数为初始化的值(子组件回调函数改变列表表头)
解决方案:将表头数组初始化数据深拷贝,传给子组件
子组件
<template>
<a-modal
title="列表配置"
width="600px"
:visible="visible"
@ok="handleSubmit"
okText="确认"
@cancel="handleCancel"
cancelText="关闭"
destroyOnClose
>
<div class="table-page-search-wrapper">
<div>请选择需要的列表项</div>
<a-checkbox-group @change="onChange" v-model="columnList" style="margin-top:15px;margin-left:10px">
<a-col v-for="(item,index) in dataCloums" :key="index" style="margin-top:5px" :span="8" v-if="item.dataIndex !== 'action' && item.dataIndex !== undefined">
<a-checkbox :value="item.dataIndex" :disabled="item.dataIndex == keyClounms" >
{{ item.title }}
</a-checkbox>
</a-col>
</a-checkbox-group>
</div>
</a-modal>
</template>
<script>
export default {
components: {
},
props: {
keyClounms: { // 必选的一列,该列的dataIndex,自适应栏
type: String,
default: '',
required: true
},
// dataCloums: { // 传入组件的完整的列表
// type: Array,
// default: () => {
// return []
// },
// required: true
// }
},
data() {
return {
visible: false,
title: '',
dataCloums: [], // 需要遍历的数据
columnList: [this.keyClounms], // 已经选中的数据
list: [], // 回调返回给父组件的数据
listClounms: []
}
},
watch: {
visible() { }
},
created() {
},
methods: {
add(columns, cloneColumn) {
this.visible = true
this.list = []
for (let i = 0; i < cloneColumn.length; i++) {
if (cloneColumn[i].title == '#') {
this.list.push(cloneColumn[i])
}
}
this.dataCloums = cloneColumn
},
unique(arr) {
const res = new Map()
return arr.filter((arr) => !res.has(arr.title) && res.set(arr.title, 1));
},
onChange(checkedValues) {
this.columnList = checkedValues
},
handleSubmit() {
this.visible = false
for (let i = 0; i < this.dataCloums.length; i++) {
this.columnList.forEach(item => {
if (this.dataCloums[i].dataIndex == item) {
this.list.push(this.dataCloums[i])
}
})
}
for (let i = 0; i < this.dataCloums.length; i++) {
if (this.dataCloums[i].dataIndex == 'action') {
this.list.push(this.dataCloums[i])
}
}
this.$emit('ok', this.unique(this.list))
},
handleCancel() {
this.visible = false
}
}
}
</script>
<style lang="less" scoped>
</style>
父组件
<list-configuration ref="listConfiguration" :keyClounms="keyClounms" @ok="handleColumns"/>
this.cloneColumn = deepClone(this.columns) // 深复制列表表头数组 //created()
listConfiguration() {
this.$refs.listConfiguration.add(this.columns, this.cloneColumn)
},
handleColumns(val) {
this.columns = val
},
深复制
/*
* 深拷贝
*
**/
export function deepClone(target) {
let result;
if (typeof target === 'object') {
if (Array.isArray(target)) {
result = [];
for (let i in target) {
result.push(deepClone(target[i]))
}
} else if (target === null) {
result = null;
} else if (target.constructor === RegExp) {
result = target;
} else {
result = {};
for (let i in target) {
result[i] = deepClone(target[i]);
}
}
} else {
result = target;
}
return result;
}