vue3二次封装element-plus中的table组件

安装依赖

安装 element-plus

1
2
3
4
5
6
7
8
# NPM
$ npm install element-plus --save

# Yarn
$ yarn add element-plus

# pnpm
$ pnpm install element-plus

安装 @element-plus/icons-vue

1
2
# Icons
npm install @element-plus/icons-vue --save

引入依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// src/main.js
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as Icons from '@element-plus/icons-vue'
import { toLine } from './utils'
const app = createApp(App)

// 全局注册图标 牺牲一点性能
// el-icon-xxx
for (let i in Icons) {
// 注册全部组件
app.component(`el-icon-${toLine(i)}`, Icons[i])
}

app.use(ElementPlus)
app.mount('#app')

工具函数

1
2
3
4
5
6
// src/utils/index.js

// 把驼峰转换成横杠连接
export const toLine = (value) => {
return value.replace(/(A-Z)g/, '-$1').toLocaleLowerCase()
}

创建目录

  1. 在src/components/table目录下新建一个index.js作为入口文件
    1
    2
    3
    4
    5
    6
    7
    8
    9
    import { App } from 'vue'
    import table from './src/index.vue'

    // 让这个组件可以通过use的形式使用
    export default {
    install(app) {
    app.component('m-table', table)
    }
    }
  1. table组件源代码放在src/components/table/src/index.vue中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
<template>
<el-table
:data="tableData"
v-loading="isLoading"
:element-loading-text="elementLoadingText"
:element-loading-spinner="elementLoadingSpinner"
:element-loading-background="elementLoadingBackground"
:element-loading-svg="elementLoadingSvg"
:element-loading-svg-view-box="elementLoadingSvgViewBox"
@row-click="rowClick"
v-bind="$attrs">
<template v-for="(item, index) in tableOption" :key="index">
<el-table-column
v-if="item.prop && !item.action"
:label="item.label"
:prop="item.prop"
:width="item.width"
:align="item.align">
<template #default="scope">
<template v-if="scope.row.rowEdit">
<el-input size="small" v-model="scope.row[item.prop!]"></el-input>
</template>
<template v-else>
<template v-if="scope.$index + scope.column.id === currentEdit">
<div style="display: flex">
<el-input
size="small"
v-model="scope.row[item.prop!]"></el-input>
<div>
<slot
name="cellEdit"
v-if="$slots.cellEdit"
:scope="scope"></slot>
<div class="action-icon" v-else>
<el-icon-check
class="check"
@click.stop="check(scope)"></el-icon-check>
<el-icon-close
class="close"
@click.stop="close(scope)"></el-icon-close>
</div>
</div>
</div>
</template>
<template v-else>
<slot v-if="item.slot" :name="item.slot" :scope="scope"></slot>
<span v-else>{{ scope.row[item.prop!] }}</span>
<component
:is="`el-icon-${toLine(editIcon)}`"
class="edit"
v-if="item.editable"
@click.stop="clickEditIcon(scope)"></component>
</template>
</template>
</template>
</el-table-column>
</template>
<el-table-column
:label="actionOption!.label"
:width="actionOption!.width"
:align="actionOption!.align">
<template #default="scope">
<slot name="editRow" :scope="scope" v-if="scope.row.rowEdit"></slot>
<slot name="action" :scope="scope" v-else></slot>
</template>
</el-table-column>
</el-table>

<div
v-if="pagination && !isLoading"
class="pagination"
:style="{ justifyContent }">
<el-pagination
v-model:currentPage="currentPage"
:page-sizes="pageSizes"
:page-size="pageSize"
layout="total, sizes, prev, pager, next, jumper"
:total="total"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"></el-pagination>
</div>
</template>

<script lang="ts" setup>
import { PropType, computed, ref, watch, onMounted } from 'vue'
import { TableOptions } from './types'
import { toLine } from '../../../utils'
import cloneDeep from 'lodash/cloneDeep'

let props = defineProps({
// 表格配置选项
options: {
type: Array as PropType<TableOptions[]>,
required: true
},
// 表格数据
data: {
type: Array,
required: true
},
// 加载文案
elementLoadingText: {
type: String
},
// 加载图标名
elementLoadingSpinner: {
type: String
},
// 加载背景颜色
elementLoadingBackground: {
type: String
},
// 加载图标是svg
elementLoadingSvg: {
type: String
},
// 加载团是svg的配置
elementLoadingSvgViewBox: {
type: String
},
// 编辑显示的图标
editIcon: {
type: String,
default: 'Edit'
},
// 是否可以编辑行
isEditRow: {
type: Boolean,
default: false
},
// 编辑行按钮的标识
editRowIndex: {
type: String,
default: ''
},
// 是否显示分页
pagination: {
type: Boolean,
default: false
},
// 显示分页的对齐方式
paginationAlign: {
type: String as PropType<'left' | 'center' | 'right'>,
default: 'left'
},
// 当前是第几页
currentPage: {
type: Number,
default: 1
},
// 当前一页多少条数据
pageSize: {
type: Number,
default: 10
},
// 显示分页数据多少条的选项
pageSizes: {
type: Array,
default: () => [10, 20, 30, 40]
},
// 数据总条数
total: {
type: Number,
default: 0
}
})

let emits = defineEmits([
'confirm',
'cancel',
'update:editRowIndex',
'size-change',
'current-change'
])

// 分页的每一页数据变化
let handleSizeChange = (val: number) => {
emits('size-change', val)
// console.log(val)
}
// 分页页数改变
let handleCurrentChange = (val: number) => {
emits('current-change', val)
// console.log(val)
}

// 当前被点击的单元格的标识
let currentEdit = ref<string>('')

// 拷贝一份表格的数据
let tableData = ref<any[]>(cloneDeep(props.data))
// 拷贝一份按钮的标识
let cloneEditRowIndex = ref<string>(props.editRowIndex)
// 监听的标识
let watchData = ref<boolean>(false)

// 如果data的数据变了 要重新给tableData赋值
// 只需要监听一次就可以了
let stopWatchData = watch(
() => props.data,
(val) => {
watchData.value = true
tableData.value = val
tableData.value.map((item) => {
item.rowEdit = false
})
if (watchData.value) stopWatchData()
},
{ deep: true }
)

// 监听
watch(
() => props.editRowIndex,
(val) => {
if (val) cloneEditRowIndex.value = val
}
)

onMounted(() => {
tableData.value.map((item) => {
item.rowEdit = false
})
})

// 过滤操作项之后的配置
let tableOption = computed(() => props.options.filter((item) => !item.action))
// 操作项
let actionOption = computed(() => props.options.find((item) => item.action))
let currentPage = computed(() => props.currentPage)
// 是否在加载中
let isLoading = computed(() => !props.data || !props.data.length)

// 表格分页的排列方式
let justifyContent = computed(() => {
if (props.paginationAlign === 'left') return 'flex-start'
else if (props.paginationAlign === 'right') return 'flex-end'
else return 'center'
})

// 点击编辑图标
let clickEditIcon = (scope: any) => {
// console.log("🚀 ~ clickEditIcon ~ scope:", scope)

// 会做一个判断 判断是否当前单元格被点击了
// 拼接$index和column的id
currentEdit.value = scope.$index + scope.column.id
// console.log(currentEdit.value)
}

// 点击确认
let check = (scope: any) => {
emits('confirm', scope)
currentEdit.value = ''
}
// 点击取消
let close = (scope: any) => {
emits('cancel', scope)
currentEdit.value = ''
}

// 点击行的事件
let rowClick = (row: any, column: any) => {
// 判断是否是点击的操作项
if (column.label === actionOption.value!.label) {
if (props.isEditRow && cloneEditRowIndex.value === props.editRowIndex) {
// 编辑行的操作
row.rowEdit = !row.rowEdit
// 重置其他数据的rowEdit
tableData.value.map((item) => {
if (item !== row) item.rowEdit = false
})
// 重置按钮的标识
if (!row.rowEdit) emits('update:editRowIndex', '')
}
}
}
</script>

<style lang="scss" scoped>
.edit {
width: 1em;
height: 1em;
position: relative;
top: 2px;
left: 12px;
cursor: pointer;
}
.action-icon {
display: flex;
svg {
width: 1em;
height: 1em;
margin-left: 8px;
position: relative;
top: 8px;
cursor: pointer;
}
.check {
color: red;
}
.close {
color: green;
}
}
.pagination {
margin-top: 16px;
display: flex;
}
</style>

  1. 在src/components目录下新建一个index.js作为入口文件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    import { App } from 'vue'

    import table from './table'

    const components = [
    table,
    // 以后还可以有更多的组件
    ]

    export default {
    install(app) {
    components.map(item => {
    app.use(item)
    })
    }
    }
  2. 在src/main.js中引入

1
2
3
4
import mUI from './components'

app.use(mUI)

  1. 在页面中使用我们封装好的组件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
<template>
<m-table
:options="options"
:data="tableData"
elementLoadingText="加载中..."
elementLoadingBackground="rgba(0,0,0,.8)"
:element-loading-svg="svg"
element-loading-svg-view-box="-10, -10, 50, 50"
isEditRow
pagination
stripe
border
:total="total"
:currentPage="current"
:pageSize="pageSize"
v-model:editRowIndex="editRowIndex"
@confirm="confirm"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
>
<template #date="{ scope }">
<el-icon-timer></el-icon-timer>
<span style="margin-left: 10px">{{ scope.row.date }}</span>
</template>
<template #name="{ scope }">
<el-popover effect="light" trigger="hover" placement="top">
<template #default>
<p>姓名: {{ scope.row.name }}</p>
<p>住址: {{ scope.row.address }}</p>
</template>
<template #reference>
<div class="name-wrapper">
<el-tag size="medium">{{ scope.row.name }}</el-tag>
</div>
</template>
</el-popover>
</template>
<template #editRow="scope">
<el-button size="small" type="primary" @click="sure(scope.scope)">确认</el-button>
<el-button size="small" type="danger">取消</el-button>
</template>
<template #action="scope">
<el-button size="small" type="primary" @click="edit(scope.scope)">编辑</el-button>
<el-button size="small" type="danger">删除</el-button>
</template>
</m-table>
</template>

<script lang='ts' setup>
import { TableOptions } from '../../components/table/src/types'
import { ref, onMounted } from 'vue'
import axios from 'axios'

let options: TableOptions[] = [
{
prop: 'date',
label: '日期',
// width: '180',
align: 'center',
slot: 'date',
editable: true
},
{
prop: 'name',
label: '姓名',
// width: '180',
align: 'center',
slot: 'name'
},
{
prop: 'address',
label: '地址',
align: 'center',
editable: true
},
{
label: '操作',
action: true,
align: 'center'
}
]
let tableData = ref<any[]>([])
let editRowIndex = ref<string>('')
let svg = `
<path class="path" d="
M 30 15
L 28 17
M 25.61 25.61
A 15 15, 0, 0, 1, 15 30
A 15 15, 0, 1, 1, 27.99 7.5
L 15 15
" style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
`
// setTimeout(() => {
// tableData.value = [
// {
// date: '2016-05-03',
// name: 'Tom1',
// address: 'No. 189, Grove St, Los Angeles',
// },
// {
// date: '2016-05-02',
// name: 'Tom2',
// address: 'No. 189, Grove St, Los Angeles',
// },
// {
// date: '2016-05-04',
// name: 'Tom3',
// address: 'No. 189, Grove St, Los Angeles',
// },
// {
// date: '2016-05-01',
// name: 'Tom4',
// address: 'No. 189, Grove St, Los Angeles',
// },
// ]
// }, 3000)

let current = ref<number>(1)
let pageSize = ref<number>(10)
let total = ref<number>(0)
let getData = () => {
axios.post('/api/list', {
current: current.value,
pageSize: pageSize.value,
}).then((res: any) => {
if (res.data.code === '200') {
tableData.value = res.data.data.rows
total.value = res.data.data.total
console.log(res.data.data)
}
})
}
let handleSizeChange = (val: number) => {
pageSize.value = val
getData()
}
let handleCurrentChange = (val: number) => {
current.value = val
getData()
}
onMounted(() => {
getData()
})


let edit = (scope: any) => {
// console.log(scope)
editRowIndex.value = 'edit'
}
let sure = (scope: any) => {
console.log(scope)
}
let confirm = (scope: any) => {
// console.log(scope)
}
</script>

<style lang='scss' scoped>
svg {
width: 1em;
height: 1em;
}
</style>