Element?Plus組件Form表單Table表格二次封裝的完整過程
前言
直至今天,看了一下別人寫的代碼,才發(fā)現(xiàn)以前自己寫的代碼太垃圾,所以在這次做的一個(gè)后臺(tái)項(xiàng)目中,采用他的代碼風(fēng)格,怎么說呢,復(fù)用性特別好,封裝的很好,學(xué)到很多,所以記錄一下思路,我認(rèn)為這個(gè)封裝思路是真的很棒,寫第一個(gè)頁面的時(shí)候可能會(huì)麻煩一些,但是后面只要是相似的頁面,事半功倍,直接CV改配置項(xiàng)就好了,是真的頂,記錄一下,學(xué)習(xí)一下,我這里用的是vue3+ts
Form表單的封裝
簡(jiǎn)述
這里是Form表單部分,下面是完整的思路,最后有附上完整的代碼,大佬可以直接看完整的代碼就能看懂了,小白們跟著我的思路估計(jì)能看懂....
正常的使用
如果我們正常使用組件庫里面的組件會(huì)是這樣的
代碼如下
role.vue頁面組件
<template> <div class="role"> <el-form> <el-form-item label="用戶id"> <el-input placeholder="請(qǐng)輸入用戶id"></el-input> </el-form-item> <el-form-item label="用戶名"> <el-input placeholder="請(qǐng)輸入用戶名"></el-input> </el-form-item> <el-form-item label="真實(shí)姓名"> <el-input placeholder="請(qǐng)輸入真實(shí)姓名"></el-input> </el-form-item> <el-form-item label="用戶名"> <el-input placeholder="請(qǐng)輸入用戶名"></el-input> </el-form-item> <el-form-item label="電話號(hào)碼"> <el-input placeholder="請(qǐng)輸入電話號(hào)碼"></el-input> </el-form-item> <el-form-item label="用戶狀態(tài)"> <el-select placeholder="請(qǐng)選擇用戶狀態(tài)"> <el-option label="禁用" value="0"></el-option> <el-option label="啟用" value="1"></el-option> </el-select> </el-form-item> <el-form-item label="創(chuàng)建時(shí)間"> <el-date-picker startPlaceholder="開始時(shí)間" endPlaceholder="結(jié)束時(shí)間" type="daterange" ></el-date-picker> </el-form-item> </el-form> </div> </template> ? <script setup lang="ts"></script> ? <style scoped lang="less"></style>
這時(shí)我們可以加點(diǎn)樣式讓他變得好看,并且布局也變一變就可以變成這樣,當(dāng)然樣式布局可以自定義
代碼如下
role.vue頁面組件
<template> <div class="role"> <el-form labelWidth="120px"> <el-row> <el-col :span="8"> <el-form-item label="用戶id" :style="{ padding: '10px 20px' }" > <el-input placeholder="請(qǐng)輸入用戶id"></el-input> </el-form-item> </el-col> <el-col :span="8"> <el-form-item label="用戶名" :style="{ padding: '10px 20px' }" > <el-input placeholder="請(qǐng)輸入用戶名"></el-input> </el-form-item> </el-col> <el-col :span="8"> <el-form-item label="真實(shí)姓名" :style="{ padding: '10px 20px' }" > <el-input placeholder="請(qǐng)輸入真實(shí)姓名"></el-input> </el-form-item> </el-col> <el-col :span="8"> <el-form-item label="電話號(hào)碼" :style="{ padding: '10px 20px' }" > <el-input placeholder="請(qǐng)輸入電話號(hào)碼"></el-input> </el-form-item> </el-col> <el-col :span="8"> <el-form-item label="用戶狀態(tài)" :style="{ padding: '10px 20px' }" > <el-select placeholder="請(qǐng)選擇用戶狀態(tài)"> <el-option label="禁用" value="0"></el-option> <el-option label="啟用" value="1"></el-option> </el-select> </el-form-item> </el-col> <el-col :span="8"> <el-form-item label="創(chuàng)建時(shí)間" :style="{ padding: '10px 20px' }" > <el-date-picker startPlaceholder="開始時(shí)間" endPlaceholder="結(jié)束時(shí)間" type="daterange" ></el-date-picker> </el-form-item> </el-col> </el-row> </el-form> </div> </template> ? <script setup lang="ts"></script> ? <style scoped lang="less"> .el-form-item { margin-top: 18px; } .el-select { width: 100%; } </style>
開始封裝①
這時(shí)我們就可以開始封裝了,如果我們可以通過傳配置項(xiàng)的方法來控制樣式和form表單項(xiàng)的類型和個(gè)數(shù)的話,是不是變得很方便,下次直接傳配置項(xiàng)用就好了?話不多說直接上圖上代碼
可以看到效果一樣,代碼卻簡(jiǎn)潔了,模板里面不會(huì)出現(xiàn)大量重復(fù)的代碼了
role.vue頁面組件
<template> <div class="role"> <el-form :labelWidth="searchFormConfig.labelWidth"> <el-row> <template v-for="item in searchFormConfig.formItems" :key="item.label"> <el-col :span="8"> <el-form-item :label="item.label" :style="searchFormConfig.itemStyle" > <template v-if="item.type === 'input' || item.type === 'password'" > <el-input :placeholder="item.placeholder" :show-password="item.type === 'password'" ></el-input> </template> <template v-else-if="item.type === 'select'"> <el-select :placeholder="item.placeholder"> <el-option v-for="option in item.options" :key="option.value" :label="option.label" :value="option.value" ></el-option> </el-select> </template> <template v-else> <el-date-picker v-bind="item.otherOptions"></el-date-picker> </template> </el-form-item> </el-col> </template> </el-row> </el-form> </div> </template> ? <script setup lang="ts"> // 定義表單配置項(xiàng) const searchFormConfig = { formItems: [ { type: 'input', label: '用戶id', placeholder: '請(qǐng)輸入用戶id' }, { type: 'input', label: '用戶名', placeholder: '請(qǐng)輸入用戶名' }, { type: 'input', label: '真實(shí)姓名', placeholder: '請(qǐng)輸入真實(shí)姓名' }, { type: 'input', label: '電話號(hào)碼', placeholder: '請(qǐng)輸入電話號(hào)碼' }, { type: 'select', label: '用戶狀態(tài)', placeholder: '請(qǐng)選擇用戶狀態(tài)', options: [ { label: '禁用', value: 0 }, { label: '啟用', value: 1 } ] }, { type: 'datepicker', label: '創(chuàng)建時(shí)間', otherOptions: { startPlaceholder: '開始時(shí)間', endPlaceholder: '結(jié)束時(shí)間', type: 'daterange', 'unlink-panels': true } } ], labelWidth: '120px', itemStyle: { padding: '10px 20px' }, itemColLayout: { span: 8 } } </script> ? <style scoped lang="less"> .el-form-item { margin-top: 18px; } .el-select { width: 100%; } </style>
開始封裝②
這時(shí)它復(fù)用的錐形已經(jīng)有了,我們可以將配置項(xiàng)抽出去,并給它一些類型限制,把這部分使用表單的代碼抽出去,封裝成form組件,這樣之后我們?cè)谟玫臅r(shí)候,直接用這個(gè)組件然后給它傳配置項(xiàng)就可以了
1.配置項(xiàng)類型限制文件(不用ts的話就沒有,不想限制全部給any類型隨意,我這里是為了讓代碼嚴(yán)謹(jǐn)一丟丟哈哈)
type IFormType = 'input' | 'password' | 'select' | 'datepicker' ? interface IFormOption { label: string value: string | number } ? export interface IFormItem { type: IFormType //輸入框類型 label: string //輸入框標(biāo)題 placeholder?: any //輸入框默認(rèn)顯示內(nèi)容 // 針對(duì)select options?: IFormOption[] //選擇器的可選子選項(xiàng) // 針對(duì)特殊屬性 otherOptions?: any ? } ? export interface IForm { formItems: IFormItem[] labelWidth?: string itemStyle?: any itemColLayout?: any }
2.配置項(xiàng)文件
import { IForm } from '@/base-ui/form/type' export const searchFormConfig: IForm = { formItems: [ { type: 'input', label: '用戶id', placeholder: '請(qǐng)輸入用戶id' }, { type: 'input', label: '用戶名', placeholder: '請(qǐng)輸入用戶名' }, { type: 'input', label: '真實(shí)姓名', placeholder: '請(qǐng)輸入真實(shí)姓名' }, { type: 'input', label: '電話號(hào)碼', placeholder: '請(qǐng)輸入電話號(hào)碼' }, { type: 'select', label: '用戶狀態(tài)', placeholder: '請(qǐng)選擇用戶狀態(tài)', options: [ { label: '啟用', value: 1 }, { label: '禁用', value: 0 } ] }, { type: 'datepicker', label: '創(chuàng)建時(shí)間', otherOptions: { startPlaceholder: '開始時(shí)間', endPlaceholder: '結(jié)束時(shí)間', type: 'daterange' } } ], labelWidth: '120px', itemColLayout: { span: 8 }, itemStyle: { padding: '10px 20px' } }
3.form表單文件
注意:在這里,我將labelWidth,itemColLayout,itemStyle設(shè)置了默認(rèn)值,所以我上面的那些樣式配置項(xiàng)可以不傳,默認(rèn)就是我設(shè)置的那些值,如果需要?jiǎng)e的樣式可以傳入修改,不要樣式可以傳個(gè)空進(jìn)去,這里我還加了兩個(gè)插槽,增加可擴(kuò)展性
<template> <div class="header"> <slot name="header"> </slot> </div> <el-form ref="ruleFormRef" :labelWidth="labelWidth"> <el-row> <template v-for="item in formItems" :key="item.label"> <el-col v-bind="itemColLayout"> <el-form-item v-if="!item.isHidden" :label="item.label" :style="itemStyle" :prop="item.field" > <template v-if="item.type === 'input' || item.type === 'password'"> <el-input :placeholder="item.placeholder" :show-password="item.type === 'password'" ></el-input> </template> <template v-else-if="item.type === 'select'"> <el-select :placeholder="item.placeholder"> <el-option v-for="option in item.options" :key="option.label" :label="option.label" :value="option.value" ></el-option> </el-select> </template> <template v-if="item.type === 'datepicker'"> <el-date-picker v-bind="item.otherOptions"></el-date-picker> </template> </el-form-item> </el-col> </template> </el-row> </el-form> <div class="footer"> <slot name="footer"></slot> </div> </template> ? <script setup lang="ts"> import { defineProps, withDefaults } from 'vue' import { IFormItem } from './type' interface Prop { formItems: IFormItem[] // 表單配置項(xiàng) labelWidth?: string // 每個(gè)表單標(biāo)題寬度 itemStyle?: object // 每個(gè)表單樣式 itemColLayout?: object // 表單布局 isHidden?: boolean // 該輸入框是否隱藏 } const props = withDefaults(defineProps<Prop>(), { labelWidth: '120px', itemColLayout: () => ({ xl: 6, // >=1920px lg: 8, // >=1200px md: 12, // >=992px sm: 24, // >=768px xs: 24 // <768px }), itemStyle: () => ({ padding: '10px 20px' }) }) </script> ? <style scoped> .el-form-item { margin-top: 18px; } .el-select { width: 100%; } </style>
4.role.vue頁面組件
<template> <div class="role"> <form-test v-bind="searchFormConfig"></form-test> </div> </template> ? <script setup lang="ts"> import formTest from '@/base-ui/form/form-test.vue' import { searchFormConfig } from './config/search-config-test' </script> ? <style scoped lang="less"></style>
這時(shí)已經(jīng)初步封裝好了,我們可以使用一下看效果,我們可以看到樣式跟之前完全一樣,但是頁面的代碼量就那么點(diǎn),要用的話直接用我們封裝好的form組件然后傳入配置項(xiàng)就出來了
它的可擴(kuò)展性也是很強(qiáng)的,比如:
這里我們把樣式配置項(xiàng)全部傳空值,然后配置項(xiàng)也傳一個(gè),它又變成原來最丑的樣子了,證明我們是可以隨意更改它的樣式和布局,只需要通過傳入配置項(xiàng)更改就可以了,方便
配置項(xiàng)文件
import { IForm } from '@/base-ui/form/type' export const searchFormConfig: IForm = { formItems: [ { field: 'id', type: 'input', label: '用戶id', placeholder: '請(qǐng)輸入用戶id' } ], labelWidth: '', itemColLayout: {}, itemStyle: {} }
其實(shí)到這里還沒結(jié)束,因?yàn)檫@時(shí)的表單還輸入不了東西,因?yàn)槲覀兏揪蜎]給它的輸入框綁定值,所以我們要在配置項(xiàng)傳入多一個(gè)field字段,它可以作為輸入框綁定的值
開始封裝③
這里僅僅是給配置項(xiàng)中增加field字段(注意如果用了ts的還要去type文件里面給我們定義的IFormItem接口添加一個(gè)field字段)
配置項(xiàng)文件
import { IForm } from '@/base-ui/form/type' export const searchFormConfig: IForm = { formItems: [ { field: 'id', type: 'input', label: '用戶id', placeholder: '請(qǐng)輸入用戶id' }, { field: 'name', type: 'input', label: '用戶名', placeholder: '請(qǐng)輸入用戶名' }, { field: 'realname', type: 'input', label: '真實(shí)姓名', placeholder: '請(qǐng)輸入真實(shí)姓名' }, { field: 'cellphone', type: 'input', label: '電話號(hào)碼', placeholder: '請(qǐng)輸入電話號(hào)碼' }, { field: 'enable', type: 'select', label: '用戶狀態(tài)', placeholder: '請(qǐng)選擇用戶狀態(tài)', options: [ { label: '啟用', value: 1 }, { label: '禁用', value: 0 } ] }, { field: 'createAt', type: 'datepicker', label: '創(chuàng)建時(shí)間', otherOptions: { startPlaceholder: '開始時(shí)間', endPlaceholder: '結(jié)束時(shí)間', type: 'daterange' } } ], labelWidth: '120px', itemColLayout: { span: 8 }, itemStyle: { padding: '10px 20px' } }
因?yàn)閭魅肓薴ied字段,所以我們要收集所有的field字段,組成formData數(shù)據(jù),傳入表單組件,formData里面的每個(gè)子項(xiàng)分別作為每個(gè)輸入框綁定的值
注意:這里有兩個(gè)難點(diǎn)
難點(diǎn)一:
我們傳進(jìn)去的數(shù)據(jù)在里面是要做修改傳出來的,而vue的原則是單項(xiàng)數(shù)據(jù)流傳輸,我們不能直接將數(shù)據(jù)傳進(jìn)去(其實(shí)事實(shí)可以這樣做,但是違背了單向數(shù)據(jù)流傳輸原則,我們盡量不違背哈),所以我們采用v-model的方式將formData傳入form組件,這樣做的話就是雙向判定了,不算違背嘿嘿
難點(diǎn)二:因?yàn)槲覀儌鬟M(jìn)去的formData的數(shù)據(jù),并不是在form組件里面用的,而是要綁定到form組件里面的element puls的輸入框里面的,所以我們?cè)趂orm組件里面接收到formData數(shù)據(jù),然后在把formData它的各個(gè)子項(xiàng)v-model綁定到輸入框里面,但是這樣會(huì)報(bào)錯(cuò),不能直接用v-model,這里就需要知道v-model是怎么實(shí)現(xiàn)的了,我們?cè)谶@里是直接把接收到的formData數(shù)據(jù)綁定到輸入框里面的,在form組件并沒有定義formData這個(gè)變量,所以不能直接用v-model的方法,這了可能有點(diǎn)懵,舉個(gè)例子
(比如你將一個(gè)值test用v-model傳入一個(gè)input的框,你輸入框輸入數(shù)據(jù),你的test是會(huì)同步改變,也就是說,v-model會(huì)把你修改后的值傳出來賦值給你的test,而在這里,我們將formData用v-model綁定到輸入框,輸入框值改變,正常來說它會(huì)將修改后的值賦值給我們傳進(jìn)去的formData,但是我們不能讓它直接賦值給我們的formData,因?yàn)槲覀兊膄ormData也是從別的組件傳進(jìn)來的,所以我們要把修改后的值再次傳出去到傳進(jìn)來formData數(shù)據(jù)的那個(gè)組件中,而不是直接就賦值,這時(shí)我們就要用到v-model的原始寫法了,其實(shí)v-model是個(gè)語法糖來的)
form.vue組件
<template> <div class="header"> <slot name="header"> </slot> </div> <el-form ref="ruleFormRef" :labelWidth="labelWidth"> <el-row> <template v-for="item in formItems" :key="item.label"> <el-col v-bind="itemColLayout"> <el-form-item v-if="!item.isHidden" :label="item.label" :style="itemStyle" > <template v-if="item.type === 'input' || item.type === 'password'"> <el-input :placeholder="item.placeholder" :show-password="item.type === 'password'" :model-value="modelValue[`${item.field}`]" @update:modelValue="valueChange($event, item.field)" ></el-input> </template> <template v-else-if="item.type === 'select'"> <el-select :placeholder="item.placeholder" :model-value="modelValue[`${item.field}`]" @update:modelValue="valueChange($event, item.field)" > <el-option v-for="option in item.options" :key="option.label" :label="option.label" :value="option.value" ></el-option> </el-select> </template> <template v-if="item.type === 'datepicker'"> <el-date-picker v-bind="item.otherOptions" :model-value="modelValue[`${item.field}`]" @update:modelValue="valueChange($event, item.field)" ></el-date-picker> </template> </el-form-item> </el-col> </template> </el-row> </el-form> <div class="footer"> <slot name="footer"></slot> </div> </template> ? <script setup lang="ts"> import { defineProps, withDefaults, defineEmits } from 'vue' import { IFormItem } from './type' interface Prop { formItems: IFormItem[] // 表單配置項(xiàng) labelWidth?: string // 每個(gè)表單標(biāo)題寬度 itemStyle?: object // 每個(gè)表單樣式 itemColLayout?: object // 表單布局 isHidden?: boolean // 該輸入框是否隱藏 modelValue: object //綁定表單的每個(gè)數(shù)據(jù) } const props = withDefaults(defineProps<Prop>(), { labelWidth: '120px', itemColLayout: () => ({ xl: 6, // >=1920px lg: 8, // >=1200px md: 12, // >=992px sm: 24, // >=768px xs: 24 // <768px }), itemStyle: () => ({ padding: '10px 20px' }) }) const emit = defineEmits<{ (e: 'update:modelValue', value: any): void }>() ? // 輸入框值改變?cè)摵瘮?shù)都會(huì)觸發(fā),將改變后的值傳出去 const valueChange = (value: any, field: string) => { emit('update:modelValue', { ...props.modelValue, [field]: value }) } </script> ? <style scoped> .el-form-item { margin-top: 18px; } .el-select { width: 100%; } </style>
role.vue頁面組件
<template> <div class="role"> <form-test v-bind="searchFormConfig" v-model="formData"></form-test> </div> </template> ? <script setup lang="ts"> import formTest from '@/base-ui/form/form-test.vue' import { searchFormConfig } from './config/search-config-test' import { ref } from 'vue' // 在這里取出所有的field字段組成formData數(shù)據(jù) const formItems = searchFormConfig.formItems ?? [] ? let formDataInit = {} formItems.map((item) => { formDataInit[item.field] = '' }) let formData = ref(formDataInit) </script> ? <style scoped lang="less"></style>
這時(shí)我們發(fā)現(xiàn)它可以拿到數(shù)據(jù)了,很nice,其實(shí)這差不多已經(jīng)算封裝好了,可以通過配置項(xiàng)修改里面的東西了,同時(shí)也可以拿到數(shù)據(jù),但是我這個(gè)項(xiàng)目不止于此,我這其實(shí)要做表單的查詢的,所以我要改裝一下變成這樣
其實(shí)就是加了兩個(gè)插槽和兩個(gè)方法,我這里要實(shí)現(xiàn)功能就是點(diǎn)擊重置按鈕,它會(huì)重置表單數(shù)據(jù),點(diǎn)擊搜索按鈕就可以拿到表單數(shù)據(jù),這樣我們就可以用我們拿到的表單數(shù)據(jù)去進(jìn)行我們的操作拉,所以上代碼
role.vue組件
該部分我們傳入了兩個(gè)template,一個(gè)是標(biāo)題:高級(jí)檢索,一個(gè)是兩個(gè)按鈕
這里要重置按鈕重置表單數(shù)據(jù),取到表單的ref調(diào)用resetFields方法就好了,然后點(diǎn)擊搜索按鈕可以打印出formData數(shù)據(jù),然后我們就可以利用該數(shù)據(jù)去做我們想要做的操作了,例如查詢列表數(shù)據(jù)等
<template> <div class="role"> <form-test v-bind="searchFormConfig" v-model="formData" ref="formTestRef"> <template #header> <div class="header"> <h1>高級(jí)檢索</h1> </div> </template> <template #footer> <div class="footer"> <el-button type="primary" :icon="Refresh" @click="resetBtnClick" >重置</el-button > <el-button type="primary" :icon="Search" @click="searchBtnClick" >搜索</el-button > </div> </template> </form-test> </div> </template> ? <script setup lang="ts"> import formTest from '@/base-ui/form/form-test.vue' import { searchFormConfig } from './config/search-config-test' import { ref } from 'vue' import { Search, Refresh } from '@element-plus/icons-vue' // 在這里取出所有的field字段組成formData數(shù)據(jù) const formItems = searchFormConfig.formItems ?? [] ? let formDataInit = {} formItems.map((item) => { formDataInit[item.field] = '' }) let formData = ref(formDataInit) ? const formTestRef = ref<InstanceType<typeof formTest>>() ? // 重置點(diǎn)擊 const resetBtnClick = () => { formTestRef.value?.resetForm() } // 搜索點(diǎn)擊 const searchBtnClick = () => { // 這里需要遍歷搜索配置項(xiàng),配置項(xiàng)里可以傳dataType,要求數(shù)據(jù)返回什么類型的數(shù)據(jù) let queryInfo = { ...formData.value } searchFormConfig.formItems.map((item: any) => { if (item.dataType === 'number' && queryInfo[item.field] !== '') { queryInfo[item.field] = Number(queryInfo[item.field]) } }) // 清空queryInfo中沒有值的屬性 for (const i in queryInfo) { if (queryInfo[i] === '') { delete queryInfo[i] } } console.log(queryInfo) } </script> ? <style scoped lang="less"> .header { padding-top: 20px; } .footer { text-align: right; padding: 0 50px 20px 0; } </style>
form.vue
<template> <div class="header"> <slot name="header"> </slot> </div> <el-form ref="ruleFormRef" :labelWidth="labelWidth" :model="modelValue"> <el-row> <template v-for="item in formItems" :key="item.label"> <el-col v-bind="itemColLayout"> <el-form-item v-if="!item.isHidden" :label="item.label" :style="itemStyle" :prop="item.field" > <template v-if="item.type === 'input' || item.type === 'password'"> <el-input :placeholder="item.placeholder" :show-password="item.type === 'password'" :model-value="modelValue[`${item.field}`]" @update:modelValue="valueChange($event, item.field)" ></el-input> </template> <template v-else-if="item.type === 'select'"> <el-select :placeholder="item.placeholder" :model-value="modelValue[`${item.field}`]" @update:modelValue="valueChange($event, item.field)" > <el-option v-for="option in item.options" :key="option.label" :label="option.label" :value="option.value" ></el-option> </el-select> </template> <template v-if="item.type === 'datepicker'"> <el-date-picker v-bind="item.otherOptions" :model-value="modelValue[`${item.field}`]" @update:modelValue="valueChange($event, item.field)" ></el-date-picker> </template> </el-form-item> </el-col> </template> </el-row> </el-form> <div class="footer"> <slot name="footer"></slot> </div> </template> ? <script setup lang="ts"> import { defineProps, withDefaults, defineEmits, ref, defineExpose } from 'vue' import { IFormItem } from './type' import type { FormInstance } from 'element-plus' ? interface Prop { formItems: IFormItem[] // 表單配置項(xiàng) labelWidth?: string // 每個(gè)表單標(biāo)題寬度 itemStyle?: object // 每個(gè)表單樣式 itemColLayout?: object // 表單布局 isHidden?: boolean // 該輸入框是否隱藏 modelValue: object //綁定表單的每個(gè)數(shù)據(jù) } const props = withDefaults(defineProps<Prop>(), { labelWidth: '120px', itemColLayout: () => ({ xl: 6, // >=1920px lg: 8, // >=1200px md: 12, // >=992px sm: 24, // >=768px xs: 24 // <768px }), itemStyle: () => ({ padding: '10px 20px' }) }) const emit = defineEmits<{ (e: 'update:modelValue', value: any): void }>() const ruleFormRef = ref<FormInstance>() ? // 輸入框值改變?cè)摵瘮?shù)都會(huì)觸發(fā),將改變后的值傳出去 const valueChange = (value: any, field: string) => { emit('update:modelValue', { ...props.modelValue, [field]: value }) } ? // 表單重置方法 const resetForm = () => { ruleFormRef.value?.resetFields() } defineExpose({ resetForm }) </script> ? <style scoped> .el-form-item { margin-top: 18px; } .el-select { width: 100%; } </style>
1.該組件要添加表單重置的方法
2.把formData的值綁定到form表單上:model=‘formData’
3.給el-form-item加上prop屬性
2,3如果不加上的話,表單內(nèi)置的重置表單方法會(huì)失效
這時(shí)我們已經(jīng)封裝完成了,但是我們可以發(fā)現(xiàn),我們的role組件東西有點(diǎn)多了,如果我們其他組件比如,user組件等,都要用這樣類似的布局,我們這時(shí)就又要把這一堆代碼給cv一遍,所以我們有可以把role里面這堆東西再封裝一次
開始封裝④
page-search.vue組件
<template> <Bu-form v-bind="searchFormConfig" v-model="formData" ref="BuFormRef"> <template #header> <div class="header"> <h1>高級(jí)檢索</h1> </div> </template> <template #footer> <div class="footer"> <el-button type="primary" :icon="Refresh" @click="resetBtnClick" >重置</el-button > <el-button type="primary" :icon="Search" @click="searchBtnClick" >搜索</el-button > </div> </template> </Bu-form> </template> ? <script setup lang="ts"> import { Search, Refresh } from '@element-plus/icons-vue' import BuForm from '@/base-ui/form/form-test.vue' import { defineProps, ref, defineEmits } from 'vue' import { useStore } from '@/store' interface Prop { searchFormConfig: any } const props = defineProps<Prop>() const emit = defineEmits<{ (e: 'resetBtnClick'): void (e: 'searchBtnClick', formData: object): void }>() const store = useStore() const BuFormRef = ref<InstanceType<typeof BuForm>>() ? const formItems = props.searchFormConfig?.formItems ?? [] ? let formDataInit = {} formItems.map((item: any) => { formDataInit[item.field] = '' }) let formData = ref(formDataInit) ? // 重置點(diǎn)擊 const resetBtnClick = () => { BuFormRef.value?.resetForm() emit('resetBtnClick') } // 搜索點(diǎn)擊 const searchBtnClick = () => { // 這里需要遍歷搜索配置項(xiàng),配置項(xiàng)里可以傳dataType,要求數(shù)據(jù)返回什么類型的數(shù)據(jù) let queryInfo = { ...formData.value } props.searchFormConfig.formItems.map((item: any) => { if (item.dataType === 'number' && queryInfo[item.field] !== '') { queryInfo[item.field] = Number(queryInfo[item.field]) } }) // 清空queryInfo中沒有值的屬性 for (const i in queryInfo) { if (queryInfo[i] === '') { delete queryInfo[i] } } emit('searchBtnClick', queryInfo) } </script> ? <style scoped> .header { padding-top: 20px; } .footer { text-align: right; padding: 0 50px 20px 0; } </style>
role.vue組件
<template> <div class="role"> <page-search-test :searchFormConfig="searchFormConfig" @resetBtnClick="handlerReset" @searchBtnClick="handlerSearch" ></page-search-test> </div> </template> ? <script setup lang="ts"> import { searchFormConfig } from './config/search-config-test' import pageSearchTest from '@/components/page-search/page-search-test.vue' const handlerReset = () => { console.log('點(diǎn)擊了重置按鈕') } const handlerSearch = (queryInfo: any) => { console.log('點(diǎn)擊了搜索按鈕,值為:', queryInfo) } </script> ? <style scoped lang="less"></style>
效果圖
這里我們就可以體會(huì)到了,一樣的效果,role里面的代碼是這么的少,只需要傳入配置項(xiàng)就可以搞出這個(gè)表單,而且還能拿到表單數(shù)據(jù),而且重點(diǎn)是,下個(gè)頁面再用這個(gè)布局,直接用page-search組件就可以了,只需要傳入不同的配置項(xiàng),如果不同布局,再封裝另一個(gè)page-search就是了,但是這是后臺(tái)耶?搞那么華麗呼哨?不就是搜索表單,展示表單么
下面附上完整全部封裝代碼
完整封裝代碼⑤
配置項(xiàng)類型文件
// type.ts ? type IFormType = 'input' | 'password' | 'select' | 'datepicker' ? interface IFormOption { label: string value: string | number } ? export interface IFormItem { field: string //字段名 type: IFormType //輸入框類型 dataType?: string //輸入框返回?cái)?shù)據(jù)類型 label: string //輸入框標(biāo)題 rules?: any[] //輸入框驗(yàn)證規(guī)則 placeholder?: any //輸入框默認(rèn)顯示內(nèi)容 // 針對(duì)select options?: IFormOption[] //選擇器的可選子選項(xiàng) // 針對(duì)特殊屬性 otherOptions?: any // 該行是否隱藏 isHidden?: boolean } ? export interface IForm { formItems: IFormItem[] labelWidth?: string itemStyle?: any itemColLayout?: any }
配置項(xiàng)文件
import { IForm } from '@/base-ui/form/type' export const searchFormConfig: IForm = { formItems: [ { field: 'id', type: 'input', label: '用戶id', placeholder: '請(qǐng)輸入用戶id' }, { field: 'name', type: 'input', label: '用戶名', placeholder: '請(qǐng)輸入用戶名' }, { field: 'realname', type: 'input', label: '真實(shí)姓名', placeholder: '請(qǐng)輸入真實(shí)姓名' }, { field: 'cellphone', type: 'input', label: '電話號(hào)碼', placeholder: '請(qǐng)輸入電話號(hào)碼' }, { field: 'enable', type: 'select', label: '用戶狀態(tài)', placeholder: '請(qǐng)選擇用戶狀態(tài)', options: [ { label: '啟用', value: 1 }, { label: '禁用', value: 0 } ] }, { field: 'createAt', type: 'datepicker', label: '創(chuàng)建時(shí)間', otherOptions: { startPlaceholder: '開始時(shí)間', endPlaceholder: '結(jié)束時(shí)間', type: 'daterange' } } ] }
form表單組件文件
<template> <div class="header"> <slot name="header"> </slot> </div> <el-form :label-width="labelWidth" ref="ruleFormRef" status-icon :model="modelValue" > <el-row> <template v-for="item in formItems" :key="item.label"> <el-col v-bind="itemColLayout"> <el-form-item v-if="!item.isHidden" :label="item.label" :rules="item.rules" :style="itemStyle" :prop="item.field" > <template v-if="item.type === 'input' || item.type === 'password'"> <el-input :placeholder="item.placeholder" :show-password="item.type === 'password'" :model-value="modelValue[`${item.field}`]" @update:modelValue="valueChange($event, item.field)" clearable /> </template> <template v-else-if="item.type === 'select'"> <el-select :placeholder="item.placeholder" :model-value="modelValue[`${item.field}`]" @update:modelValue="valueChange($event, item.field)" style="width: 100%" clearable > <el-option v-for="option in item.options" :key="option.value" :value="option.value" :label="option.label" > </el-option> </el-select> </template> <template v-else-if="item.type === 'datepicker'"> <el-date-picker unlink-panels v-bind="item.otherOptions" :model-value="modelValue[`${item.field}`]" @update:modelValue="valueChange($event, item.field)" ></el-date-picker> </template> </el-form-item> </el-col> </template> </el-row> </el-form> <div class="footer"> <slot name="footer"></slot> </div> </template> ? <script setup lang="ts"> import { IFormItem } from './type' import { defineProps, withDefaults, ref, defineEmits, defineExpose } from 'vue' import type { FormInstance } from 'element-plus' ? // 定義屬性 interface Props { formItems: IFormItem[] // 表單配置項(xiàng) labelWidth?: string // 每個(gè)表單標(biāo)題寬度 itemStyle?: object // 每個(gè)表單樣式 itemColLayout?: object // 表單布局 modelValue: object //綁定表單的每個(gè)數(shù)據(jù) isHidden?: boolean } const props = withDefaults(defineProps<Props>(), { formItems: () => [], labelWidth: '120px', itemStyle: () => ({ padding: '10px 20px' }), itemColLayout: () => ({ xl: 6, // >=1920px lg: 8, // >=1200px md: 12, // >=992px sm: 24, // >=768px xs: 24 // <768px }) }) const emit = defineEmits<{ (e: 'update:modelValue', value: any): void }>() ? const ruleFormRef = ref<FormInstance>() ? // 定義方法 const valueChange = (value: any, field: string) => { emit('update:modelValue', { ...props.modelValue, [field]: value }) } ? // 表單重置方法 const resetForm = () => { ruleFormRef.value?.resetFields() } defineExpose({ resetForm }) </script> ? <style scoped lang="less"> .el-form-item { margin-top: 18px; } </style>
page-search組件文件
<template> <div class="page-search"> <Bu-form v-bind="searchFormConfig" v-model="formData" ref="BuFormRef"> <template #header> <div class="header"> <h1>高級(jí)檢索</h1> </div> </template> <template #footer> <div class="footer"> <el-button type="primary" :icon="Refresh" @click="resetClick" >重置</el-button > <el-button type="primary" :icon="Search" @click="searchClick" >搜索</el-button > </div> </template> </Bu-form> </div> </template> ? <script setup lang="ts"> import { useStore } from '@/store' import BuForm from '@/base-ui/form/form.vue' import { Search, Refresh } from '@element-plus/icons-vue' import { ref, defineProps, defineEmits } from 'vue' import { IForm } from '@/base-ui/form/type' ? // 定義屬性 interface Props { searchFormConfig: IForm } const props = defineProps<Props>() const emit = defineEmits<{ (e: 'resetBtnClick'): void (e: 'searchBtnClick', formData: object): void }>() const store = useStore() const BuFormRef = ref<InstanceType<typeof BuForm>>() ? // 1.從接收到的搜索配置中取出各個(gè)field,組成表單的數(shù)據(jù)formData const formItems = props.searchFormConfig?.formItems ?? [] let formDataInit = {} formItems.map((item) => { formDataInit[item.field] = '' }) let formData = ref(formDataInit) ? // 2.重置與搜索功能 // 重置按鈕觸發(fā) const resetClick = () => { BuFormRef.value?.resetForm() emit('resetBtnClick') } // 搜索按鈕觸發(fā) const searchClick = () => { // 這里需要遍歷搜索配置項(xiàng),配置項(xiàng)里可以傳dataType,要求數(shù)據(jù)返回什么類型的數(shù)據(jù) let queryInfo = { ...formData.value } props.searchFormConfig.formItems.map((item) => { if (item.dataType === 'number' && queryInfo[item.field] !== '') { queryInfo[item.field] = Number(queryInfo[item.field]) } }) // 清空queryInfo中沒有值的屬性 for (const i in queryInfo) { if (queryInfo[i] === '') { delete queryInfo[i] } } emit('searchBtnClick', queryInfo) } </script> ? <style scoped> .header { padding-top: 20px; } .footer { text-align: right; padding: 0 50px 20px 0; } </style>
role頁面組件文件
<template> <div class="role"> <page-search :searchFormConfig="searchFormConfig" @resetBtnClick="handlerReset" @searchBtnClick="handlerSearch" ></page-search> </div> </template> ? <script setup lang="ts"> import { searchFormConfig } from './config/search-config-test' import pageSearch from '@/components/page-search/page-search.vue' const handlerReset = () => { console.log('點(diǎn)擊了重置按鈕') } const handlerSearch = (queryInfo: any) => { console.log('點(diǎn)擊了搜索按鈕,值為:', queryInfo) } </script> ? <style scoped lang="less"></style>
結(jié)語
寫了這么多,終于寫完了,這里是屬于Form表單部分的封裝全部過程,能寫到這其實(shí)我挺有成就感的哈哈哈哈,因?yàn)槲覄倢W(xué)會(huì)的時(shí)候思路有了,但是敲出來有點(diǎn)困難,不過這個(gè)過程是我又捋了一遍,然后自己敲出來的,感覺其實(shí)也不難,已經(jīng)掌握了這種封裝思路與方法了哈哈,其他組件其實(shí)也可以利用這種思路,封裝出來,在頁面上的使用直接傳配置項(xiàng)調(diào)用就完事,開發(fā)每個(gè)相似的頁面效率簡(jiǎn)直是牛逼
Table表格的封裝
簡(jiǎn)述
再來折磨一遍,這里是table表單的封裝,其實(shí)跟上面的差不多,有點(diǎn)小區(qū)別,會(huì)用到添加動(dòng)態(tài)插槽,這里就不墨跡了,直接上用配置項(xiàng)封裝前的正常使用
正常使用
user.vue
<template> <div class="user"> <el-table style="width: 100%" :data="dataList" border> <!-- 1.傳入showSelectColumn時(shí)展示的全選列 --> <template v-if="contentTableConfig.showSelectColumn"> <el-table-column type="selection" /> </template> <!-- 2.傳入showIndexColumn時(shí)展示的序號(hào)列 --> <template v-if="contentTableConfig.showIndexColumn"> <el-table-column type="index" label="序號(hào)" /> </template> <!-- 3.propList里面的所有列 --> <template v-for="item in contentTableConfig.propList" :key="item.prop"> <el-table-column v-bind="item" show-overflow-tooltip> <!-- 傳有slotName時(shí)展示的插槽列 --> <template #default="scope" v-if="item.slotName"> <template v-if="item.slotName === 'handler'"> <el-button size="small" :icon="Edit" type="text">編輯</el-button> <el-button size="small" :icon="Delete" type="text" >刪除</el-button > </template> <template v-if="item.slotName === 'status'"> <el-button>{{ scope.row.status === 0 ? '禁用' : '啟用' }}</el-button> </template> </template> </el-table-column> </template> </el-table> </div> </template> ? <script setup lang="ts"> import { Delete, Edit } from '@element-plus/icons-vue' import { useStore } from '@/store' import { computed } from 'vue' const store = useStore() // 這里是網(wǎng)絡(luò)請(qǐng)求數(shù)據(jù) const getPageData = () => { store.dispatch(`main/getPageListAction`, { queryInfo: { offset: 0, size: 10 }, pageName: 'users' }) } // 頁面加載時(shí)第一次調(diào)用獲取表單數(shù)據(jù) getPageData() const dataList = computed(() => store.getters[`main/pageListData`]('users')) ? // 表格配置項(xiàng) const contentTableConfig = { // 表格配置 propList: [ { prop: 'id', label: '用戶id', minWidth: '100', align: 'center' }, { prop: 'name', label: '用戶名', minWidth: '100', align: 'center' }, { prop: 'realname', label: '真實(shí)姓名', minWidth: '100', align: 'center' }, { prop: 'cellphone', label: '手機(jī)號(hào)碼', minWidth: '100', align: 'center' }, { prop: 'enable', label: '狀態(tài)', minWidth: '100', slotName: 'status', align: 'center' }, { label: '操作', minWidth: '120', slotName: 'handler', align: 'center' } ], // 表格具有序號(hào)列 showIndexColumn: true, // 表格具有可選列 showSelectColumn: true } </script> ? <style scoped lang="less"></style>
從上面可以看出,主頁面的代碼有多冗余,看到就頭疼+裂開,所以開始一層封裝
開始封裝①
配置項(xiàng)類型文件
export interface ITbaleOption { prop?: string label: string minWidth?: string slotName?: string } export interface ITable { propList: ITbaleOption[] showIndexColumn?: boolean showSelectColumn?: boolean childrenProps?: object }
配置項(xiàng)文件
import { ITable } from '@/base-ui/table/type' export const contentTableConfig: ITable = { // 表格配置 propList: [ { prop: 'id', label: '用戶id', minWidth: '100' }, { prop: 'name', label: '用戶名', minWidth: '100' }, { prop: 'realname', label: '真實(shí)姓名', minWidth: '100' }, { prop: 'cellphone', label: '手機(jī)號(hào)碼', minWidth: '100' }, { prop: 'enable', label: '狀態(tài)', minWidth: '100', slotName: 'status' }, { label: '操作', minWidth: '120', slotName: 'handler' } ], // 表格具有序號(hào)列 showIndexColumn: false, // 表格具有可選列 showSelectColumn: true }
table.vue文件
<template> <el-table style="width: 100%" :data="listData" border> <!-- 1.傳入showSelectColumn時(shí)展示的全選列 --> <template v-if="showSelectColumn"> <el-table-column type="selection" /> </template> <!-- 2.傳入showIndexColumn時(shí)展示的序號(hào)列 --> <template v-if="showIndexColumn"> <el-table-column type="index" label="序號(hào)" /> </template> <!-- 3.propList里面的所有列 --> <template v-for="item in propList" :key="item.prop"> <el-table-column v-bind="item" show-overflow-tooltip> <!-- 傳有slotName時(shí)展示的插槽列 --> <template #default="scope" v-if="item.slotName"> <template v-if="item.slotName === 'handler'"> <el-button size="small" :icon="Edit" type="text">編輯</el-button> <el-button size="small" :icon="Delete" type="text">刪除</el-button> </template> <template v-if="item.slotName === 'status'"> <el-button>{{ scope.row.status === 0 ? '禁用' : '啟用' }}</el-button> </template> </template> </el-table-column> </template> </el-table> </template> ? <script setup lang="ts"> import { Delete, Edit } from '@element-plus/icons-vue' import { defineProps, withDefaults, defineEmits } from 'vue' import { ITbaleOption } from './type' interface Props { listData: any[] //表單數(shù)據(jù) propList: ITbaleOption[] //表單配置項(xiàng) showIndexColumn?: boolean //是否顯示索引列 showSelectColumn?: boolean //是否顯示全選列 childrenProps?: object // 是否有子數(shù)據(jù),樹形數(shù)據(jù)才用得到 } const props = withDefaults(defineProps<Props>(), { showIndexColumn: false, showSelectColumn: false, childrenProps: () => ({}) }) </script> ? <style scoped></style>
user.vue
<template> <div class="user"> <table-test v-bind="contentTableConfig" :listData="dataList"></table-test> </div> </template> ? <script setup lang="ts"> // 導(dǎo)入表單配置項(xiàng) import { contentTableConfig } from './config/table-config' import tableTest from '@/base-ui/table/table-test.vue' import { useStore } from '@/store' import { computed } from 'vue' const store = useStore() ? // 這里是網(wǎng)絡(luò)請(qǐng)求數(shù)據(jù) const getPageData = () => { store.dispatch(`main/getPageListAction`, { queryInfo: { offset: 0, size: 10 }, pageName: 'users' }) } // 頁面加載時(shí)第一次調(diào)用獲取表單數(shù)據(jù) getPageData() const dataList = computed(() => store.getters[`main/pageListData`]('users')) </script> ? <style scoped lang="less"></style>
可以看到,代碼抽出去了,但是我們可以發(fā)現(xiàn),里面的插槽其實(shí)不能給它寫死,應(yīng)該是動(dòng)態(tài)決定的,所以我們可以這樣做
在擁有slotName部分的插槽列部分放入一個(gè)具名插槽,再將默認(rèn)插槽列中的scope.row發(fā)回給具名插槽
table.vue(為了可擴(kuò)展性,我依舊在里面加了兩個(gè)插槽,一個(gè)頂部一個(gè)底部)
<template> <div class="header"> <slot name="header"> </slot> </div> <el-table style="width: 100%" :data="listData" border> <!-- 1.傳入showSelectColumn時(shí)展示的全選列 --> <template v-if="showSelectColumn"> <el-table-column type="selection" /> </template> <!-- 2.傳入showIndexColumn時(shí)展示的序號(hào)列 --> <template v-if="showIndexColumn"> <el-table-column type="index" label="序號(hào)" /> </template> <!-- 3.propList里面的所有列 --> <template v-for="item in propList" :key="item.prop"> <el-table-column v-bind="item" show-overflow-tooltip> <!-- 傳有slotName時(shí)展示的插槽列 --> <template #default="scope" v-if="item.slotName"> <slot :name="item.slotName" :row="scope.row"></slot> </template> </el-table-column> </template> </el-table> <div class="footer"> <slot name="footer"> </slot> </div> </template> ? <script setup lang="ts"> import { defineProps, withDefaults, defineEmits } from 'vue' import { ITbaleOption } from './type' interface Props { listData: any[] //表單數(shù)據(jù) propList: ITbaleOption[] //表單配置項(xiàng) showIndexColumn?: boolean //是否顯示索引列 showSelectColumn?: boolean //是否顯示全選列 childrenProps?: object // 是否有子數(shù)據(jù),樹形數(shù)據(jù)才用得到 } const props = withDefaults(defineProps<Props>(), { showIndexColumn: false, showSelectColumn: false, childrenProps: () => ({}) }) </script> ? <style scoped></style>
然后在user.vue中放入具名插槽,傳進(jìn)去table組件里,同時(shí)傳入一些內(nèi)容到可擴(kuò)展插槽里面
user.vue
<template> <div class="user"> <div class="content"> <table-test v-bind="contentTableConfig" :listData="dataList"> <!-- 1.header中的插槽 --> <template #header> <div class="header-default"> <!-- 傳入標(biāo)題(位于左側(cè)) --> <div class="title">用戶列表</div> <!-- 傳入處理內(nèi)容(位于右側(cè)) --> <div class="handler"> <el-button type="primary" @click="addUserBtnClick" >新建用戶</el-button > </div> </div> </template> <!-- 2.該user頁面獨(dú)有部分 --> <template #status="scope"> <el-button>{{ scope.row.status === 0 ? '禁用' : '啟用' }}</el-button> </template> <!-- 3.每個(gè)頁面都會(huì)有的部分 --> <template #handler="scope"> <el-button size="small" :icon="Edit" type="text" @click="handleEditClick(scope.row)" >編輯</el-button > <el-button size="small" :icon="Delete" type="text" @click="deleteBtnClick(scope.row)" >刪除</el-button > </template> <!-- 4.footer插槽 --> <template #footer> <!-- 只有總條數(shù)>0才會(huì)有分頁器 --> <div class="footer-default"> <el-pagination :page-sizes="[100, 200, 300, 400]" layout="total, sizes, prev, pager, next, jumper" :total="400" /> </div> </template> </table-test> </div> </div> </template> ? <script setup lang="ts"> // 導(dǎo)入表單配置項(xiàng) import { contentTableConfig } from './config/table-config' import { Delete, Edit } from '@element-plus/icons-vue' import tableTest from '@/base-ui/table/table-test.vue' import { useStore } from '@/store' import { computed } from 'vue' const store = useStore() ? // 這里是網(wǎng)絡(luò)請(qǐng)求數(shù)據(jù) const getPageData = () => { store.dispatch(`main/getPageListAction`, { queryInfo: { offset: 0, size: 10 }, pageName: 'users' }) } // 頁面加載時(shí)第一次調(diào)用獲取表單數(shù)據(jù) getPageData() const dataList = computed(() => store.getters[`main/pageListData`]('users')) ? // 點(diǎn)擊編輯按鈕觸發(fā)事件 const handleEditClick = (row: any) => { console.log('點(diǎn)擊了編輯按鈕,數(shù)據(jù)為:', row) } // 點(diǎn)擊刪除按鈕觸發(fā)事件 const deleteBtnClick = (row: any) => { console.log('點(diǎn)擊了刪除按鈕,數(shù)據(jù)為:', row) } // 點(diǎn)擊新建用戶觸發(fā)事件 const addUserBtnClick = () => { console.log('點(diǎn)擊了新建用戶') } </script> ? <style scoped lang="less"> .content { border-top: 20px solid #dedee1; padding: 40px; } .header-default { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; .title { font-size: 22px; font-weight: 700; } } .footer-default { display: flex; justify-content: flex-end; margin-top: 20px; } </style>
顯然此時(shí)封裝已經(jīng)滿足需求了,但是我們發(fā)現(xiàn)主頁面的代碼頁還是比較冗余,如果不用到插槽的話還好,要用到插槽的話,就要在主頁面寫入很多插槽,多個(gè)頁面都這樣的話頁裂開,所以我們要像之前一樣把這坨代碼再封一層
開始封裝②
page-table.vue
<template> <table-test v-bind="contentTableConfig" :listData="dataList"> <!-- 1.header中的插槽 --> <template #header> <div class="header-default"> <!-- 傳入標(biāo)題(位于左側(cè)) --> <div class="title">{{ pageNameInChinese }}列表</div> <!-- 傳入處理內(nèi)容(位于右側(cè)) --> <div class="handler"> <el-button type="primary" @click="addUserBtnClick" >新建{{ pageNameInChinese }}</el-button > </div> </div> </template> <!-- 2.該user頁面獨(dú)有部分 --> <template #status="scope"> <el-button>{{ scope.row.status === 0 ? '禁用' : '啟用' }}</el-button> </template> <!-- 3.每個(gè)頁面都會(huì)有的部分 --> <template #handler="scope"> <el-button size="small" :icon="Edit" type="text" @click="handleEditClick(scope.row)" >編輯</el-button > <el-button size="small" :icon="Delete" type="text" @click="deleteBtnClick(scope.row)" >刪除</el-button > </template> <!-- 4.footer插槽 --> <template #footer> <!-- 只有總條數(shù)>0才會(huì)有分頁器 --> <div class="footer-default"> <el-pagination :page-sizes="[100, 200, 300, 400]" layout="total, sizes, prev, pager, next, jumper" :total="400" /> </div> </template> </table-test> </template> ? <script setup lang="ts"> import { Delete, Edit } from '@element-plus/icons-vue' import tableTest from '@/base-ui/table/table-test.vue' import type { ITable } from '@/base-ui/table/type' ? import { useStore } from '@/store' import { defineProps, computed } from 'vue' ? // 定義屬性 interface Props { contentTableConfig: ITable //表單配置接收 pageName: string //表單名字接收 } const props = defineProps<Props>() ? const store = useStore() ? // 這里是網(wǎng)絡(luò)請(qǐng)求數(shù)據(jù) const getPageData = () => { store.dispatch(`main/getPageListAction`, { queryInfo: { offset: 0, size: 10 }, pageName: props.pageName }) } // 頁面加載時(shí)第一次調(diào)用獲取表單數(shù)據(jù) getPageData() const dataList = computed(() => store.getters[`main/pageListData`](props.pageName) ) ? // 1.獲取頁面中文名稱 const pageNameTransform = (pageName: string): string => { switch (pageName) { case 'users': return '用戶' default: return '' } } const pageNameInChinese = pageNameTransform(props.pageName) ? // 點(diǎn)擊編輯按鈕觸發(fā)事件 const handleEditClick = (row: any) => { console.log('點(diǎn)擊了編輯按鈕,數(shù)據(jù)為:', row) } // 點(diǎn)擊刪除按鈕觸發(fā)事件 const deleteBtnClick = (row: any) => { console.log('點(diǎn)擊了刪除按鈕,數(shù)據(jù)為:', row) } // 點(diǎn)擊新建用戶觸發(fā)事件 const addUserBtnClick = () => { console.log('點(diǎn)擊了新建用戶') } </script> ? <style scoped lang="less"> .header-default { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; .title { font-size: 22px; font-weight: 700; } } .footer-default { display: flex; justify-content: flex-end; margin-top: 20px; } </style>
user.vue
<template> <div class="user"> <div class="content"> <page-table :contentTableConfig="contentTableConfig" pageName="users" ></page-table> </div> </div> </template> ? <script setup lang="ts"> // 導(dǎo)入表單配置項(xiàng) import { contentTableConfig } from './config/table-config' import pageTable from '@/components/page-table/page-table-test.vue' </script> ? <style scoped lang="less"> .content { border-top: 20px solid #dedee1; padding: 40px; } </style>
圖中可以看出效果其實(shí)是一樣的,主頁面的代碼少了,只需要傳入配置項(xiàng)和pageName(控制網(wǎng)絡(luò)請(qǐng)求數(shù)據(jù))就可以生成一個(gè)表格,但是我們可以發(fā)現(xiàn),如果多個(gè)頁面復(fù)用的話,其實(shí)操作列的插槽是公有的,但是狀態(tài)列卻是私有的,別的頁面不一定有狀態(tài)頁,所以狀態(tài)列內(nèi)容插入的位置應(yīng)該在主頁面user里面而不該在封裝的組件里面,而且編輯新建邏輯也是頁面獨(dú)有,應(yīng)該在主頁面執(zhí)行
開始封裝③
user.vue
<template> <div class="user"> <div class="content"> <page-table :contentTableConfig="contentTableConfig" pageName="users" @editBtnClick="handleEditClick" @createBtnClick="handleCreateClick" > <template #status="scope"> <el-button>{{ scope.row.status === 0 ? '禁用' : '啟用' }}</el-button> </template> </page-table> </div> </div> </template> ? <script setup lang="ts"> // 導(dǎo)入表單配置項(xiàng) import { contentTableConfig } from './config/table-config' import pageTable from '@/components/page-table/page-table-test.vue' ? const handleEditClick = (row: any, pageNameInChinese: any) => { console.log('點(diǎn)擊了編輯按鈕,數(shù)據(jù)為:', row, pageNameInChinese) } ? const handleCreateClick = (pageNameInChinese: any) => { console.log('點(diǎn)擊了新建用戶,數(shù)據(jù)為:', pageNameInChinese) } </script> ? <style scoped lang="less"> .content { border-top: 20px solid #dedee1; padding: 40px; } </style>
page-table.vue
<template> <table-test v-bind="contentTableConfig" :listData="dataList"> <!-- 1.header中的插槽 --> <template #header> <div class="header-default"> <!-- 傳入標(biāo)題(位于左側(cè)) --> <div class="title">{{ pageNameInChinese }}列表</div> <!-- 傳入處理內(nèi)容(位于右側(cè)) --> <div class="handler"> <el-button type="primary" @click="addUserBtnClick" >新建{{ pageNameInChinese }}</el-button > </div> </div> </template> <!-- 2.該user頁面獨(dú)有部分 --> <template v-for="item in otherPropSlots" :key="item.prop" #[item.slotName]="scope" > <template v-if="item.slotName"> <slot :name="item.slotName" :row="scope.row"></slot> </template> </template> <!-- 3.每個(gè)頁面都會(huì)有的部分 --> <template #handler="scope"> <el-button size="small" :icon="Edit" type="text" @click="handleEditClick(scope.row)" >編輯</el-button > <el-button size="small" :icon="Delete" type="text" @click="deleteBtnClick(scope.row)" >刪除</el-button > </template> <!-- 4.footer插槽 --> <template #footer> <!-- 只有總條數(shù)>0才會(huì)有分頁器 --> <div class="footer-default"> <el-pagination :page-sizes="[100, 200, 300, 400]" layout="total, sizes, prev, pager, next, jumper" :total="400" /> </div> </template> </table-test> </template> ? <script setup lang="ts"> import { Delete, Edit } from '@element-plus/icons-vue' import tableTest from '@/base-ui/table/table-test.vue' import type { ITable } from '@/base-ui/table/type' ? import { useStore } from '@/store' import { defineProps, computed, defineEmits } from 'vue' ? // 定義屬性 interface Props { contentTableConfig: ITable //表單配置接收 pageName: string //表單名字接收 } const props = defineProps<Props>() const emit = defineEmits<{ (e: 'createBtnClick', pageNameInChinese: string): void (e: 'editBtnClick', rowData: any, pageNameInChinese: string): void }>() ? const store = useStore() ? // 這里是網(wǎng)絡(luò)請(qǐng)求數(shù)據(jù) const getPageData = () => { store.dispatch(`main/getPageListAction`, { queryInfo: { offset: 0, size: 10 }, pageName: props.pageName }) } // 頁面加載時(shí)第一次調(diào)用獲取表單數(shù)據(jù) getPageData() const dataList = computed(() => store.getters[`main/pageListData`](props.pageName) ) ? // 1.獲取頁面中文名稱 const pageNameTransform = (pageName: string): string => { switch (pageName) { case 'users': return '用戶' default: return '' } } const pageNameInChinese = pageNameTransform(props.pageName) ? // 2.屬于動(dòng)態(tài)插槽的配置項(xiàng)篩選 const otherPropSlots: any = props.contentTableConfig?.propList.filter( (item: any) => { if (item.slotName === 'handler') return false return item.slotName } ) ? // 點(diǎn)擊編輯按鈕觸發(fā)事件 const handleEditClick = (row: any) => { emit('editBtnClick', row, pageNameInChinese) } // 點(diǎn)擊刪除按鈕觸發(fā)事件 const deleteBtnClick = (row: any) => { console.log('點(diǎn)擊了刪除按鈕,數(shù)據(jù)為:', row) } // 點(diǎn)擊新建用戶觸發(fā)事件 const addUserBtnClick = () => { emit('createBtnClick', pageNameInChinese) } </script> ? <style scoped lang="less"> .header-default { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; .title { font-size: 22px; font-weight: 700; } } .footer-default { display: flex; justify-content: flex-end; margin-top: 20px; } </style>
可以看到,這時(shí)我們已經(jīng)把獨(dú)有私有的插槽區(qū)分開了,而且編輯和新建的邏輯也在主頁面中執(zhí)行,封裝完畢,下面附上完整代碼
完整封裝代碼④
配置項(xiàng)類型文件
export interface ITbaleOption { prop?: string label: string minWidth?: string slotName?: string align?: string } export interface ITable { propList: ITbaleOption[] showIndexColumn?: boolean showSelectColumn?: boolean childrenProps?: object }
配置項(xiàng)文件
import { ITable } from '@/base-ui/table/type' export const contentTableConfig: ITable = { // 表格配置 propList: [ { prop: 'id', label: '用戶id', minWidth: '100', align: 'center' }, { prop: 'name', label: '用戶名', minWidth: '100', align: 'center' }, { prop: 'realname', label: '真實(shí)姓名', minWidth: '100', align: 'center' }, { prop: 'cellphone', label: '手機(jī)號(hào)碼', minWidth: '100', align: 'center' }, { prop: 'enable', label: '狀態(tài)', minWidth: '100', slotName: 'status', align: 'center' }, { label: '操作', minWidth: '120', slotName: 'handler', align: 'center' } ], // 表格具有序號(hào)列 showIndexColumn: false, // 表格具有可選列 showSelectColumn: true }
table表單組件文件
<template> <div class="header"> <slot name="header"> </slot> </div> <el-table style="width: 100%" :data="listData" border> <!-- 1.傳入showSelectColumn時(shí)展示的全選列 --> <template v-if="showSelectColumn"> <el-table-column type="selection" /> </template> <!-- 2.傳入showIndexColumn時(shí)展示的序號(hào)列 --> <template v-if="showIndexColumn"> <el-table-column type="index" label="序號(hào)" /> </template> <!-- 3.propList里面的所有列 --> <template v-for="item in propList" :key="item.prop"> <el-table-column v-bind="item" show-overflow-tooltip> <!-- 傳有slotName時(shí)展示的插槽列 --> <template #default="scope" v-if="item.slotName"> <slot :name="item.slotName" :row="scope.row"></slot> </template> </el-table-column> </template> </el-table> <div class="footer"> <slot name="footer"> </slot> </div> </template> ? <script setup lang="ts"> import { defineProps, withDefaults, defineEmits } from 'vue' import { ITbaleOption } from './type' interface Props { listData: any[] //表單數(shù)據(jù) propList: ITbaleOption[] //表單配置項(xiàng) showIndexColumn?: boolean //是否顯示索引列 showSelectColumn?: boolean //是否顯示全選列 childrenProps?: object // 是否有子數(shù)據(jù),樹形數(shù)據(jù)才用得到 } const props = withDefaults(defineProps<Props>(), { showIndexColumn: false, showSelectColumn: false, childrenProps: () => ({}) }) </script> ? <style scoped></style>
page-table組件文件
user頁面組件文件
<template> <div class="user"> <div class="content"> <page-table :contentTableConfig="contentTableConfig" pageName="users" @editBtnClick="handleEditClick" @createBtnClick="handleCreateClick" > <template #status="scope"> <el-button>{{ scope.row.status === 0 ? '禁用' : '啟用' }}</el-button> </template> </page-table> </div> </div> </template> ? <script setup lang="ts"> // 導(dǎo)入表單配置項(xiàng) import { contentTableConfig } from './config/table-config' import pageTable from '@/components/page-table/page-table-test.vue' ? const handleEditClick = (row: any, pageNameInChinese: any) => { console.log('點(diǎn)擊了編輯按鈕,數(shù)據(jù)為:', row, pageNameInChinese) } ? const handleCreateClick = (pageNameInChinese: any) => { console.log('點(diǎn)擊了新建用戶,數(shù)據(jù)為:', pageNameInChinese) } </script> ? <style scoped lang="less"> .content { border-top: 20px solid #dedee1; padding: 40px; } </style>
結(jié)語
剛學(xué)會(huì)的代碼思路與寫法,花了一天整理,主要還是自己記錄一下,頗有收獲,感覺大佬分享使我進(jìn)步~雖然還是很菜....
到此這篇關(guān)于Element Plus組件Form表單Table表格二次封裝的文章就介紹到這了,更多相關(guān)Element Plus組件Table表格二次封裝內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue3?$emit用法指南(含選項(xiàng)API、組合API及?setup?語法糖)
這篇文章主要介紹了Vue3?$emit用法指南,使用?emit,我們可以觸發(fā)事件并將數(shù)據(jù)傳遞到組件的層次結(jié)構(gòu)中,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-07-07vue通過element樹形控件實(shí)現(xiàn)樹形表格
這篇文章主要為大家介紹了vue?element樹形控件實(shí)現(xiàn)樹形表格,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2021-11-11element-ui 限制日期選擇的方法(datepicker)
本篇文章主要介紹了element-ui 限制日期選擇的方法(datepicker),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-05-05vite?vue3?規(guī)范化與Git?Hooks詳解
這篇文章主要介紹了vite?vue3?規(guī)范化與Git?Hooks,本文重點(diǎn)討論?git?提交規(guī)范,結(jié)合示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-10-10Vue技巧Element Table二次封裝實(shí)戰(zhàn)示例
這篇文章主要為大家介紹了Vue技巧Element Table二次封裝實(shí)戰(zhàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11手寫?Vue3?響應(yīng)式系統(tǒng)(核心就一個(gè)數(shù)據(jù)結(jié)構(gòu))
這篇文章主要介紹了手寫?Vue3?響應(yīng)式系統(tǒng)(核心就一個(gè)數(shù)據(jù)結(jié)構(gòu)),響應(yīng)式就是被觀察的數(shù)據(jù)變化的時(shí)候做一系列聯(lián)動(dòng)處理。就像一個(gè)社會(huì)熱點(diǎn)事件,當(dāng)它有消息更新的時(shí)候,各方媒體都會(huì)跟進(jìn)做相關(guān)報(bào)道。這里社會(huì)熱點(diǎn)事件就是被觀察的目標(biāo)2022-06-06