达州市建设规划网站,咸阳做网站的公司,福建志佳建设工程发展有限公司网站,西部数码装wordpress前言
Vue 是前端开发中非常常见的一种框架#xff0c;它的易用性和灵活性使得它成为了很多开发者的首选。而在 Vue2 版本中#xff0c;组件的开发也变得非常简单#xff0c;但随着 Vue3 版本的发布#xff0c;组件开发有了更多的特性和优化#xff0c;为我们的业务开发带…前言
Vue 是前端开发中非常常见的一种框架它的易用性和灵活性使得它成为了很多开发者的首选。而在 Vue2 版本中组件的开发也变得非常简单但随着 Vue3 版本的发布组件开发有了更多的特性和优化为我们的业务开发带来了更多便利。本文将介绍如何使用 Vue3 开发业务组件并通过代码实例进行演示。
一、自己封装组件
1、button 代码 在 src 目录下创建 components 文件夹并在该文件夹下创建 Button 文件。 在Button 文件中创建 index.vue 文件和 index.ts 文件并编写以下代码 在 index.vue 文件中编写以下代码 script langts setup nameZButton
defineProps({text: {type: String,default: },btnSize: {type: String,default: default},size: {type: Number,default: 14},type: {type: String,default: default},left: {type: Number,default: 0},right: {type: Number,default: 0},disabled: {type: Boolean,default: false},loading: {type: Boolean,default: false}
})
/scripttemplatediv :typetype :sizebtnSize :classz-button-${type} :disableddisabled :loadingloading :style{marginLeft: ${left}px,marginRight: ${right}px}{{ text }}/div
/templatestyle langscss scoped
.z-button-blue {background: #80d4fb;color: #fff;border: none;:hover,:focus,:active {background: #80d4fb80;color: #fff;}.anticon {color: #fff;}
}.z-button-warn {background: #ec622b;color: #fff;border: none;outline: none;:hover,:focus,:active {background-color: #ec622b80;color: #fff;}.anticon {color: #fff;}
}
/style在 index.ts 文件中编写以下代码 import ZButton from ./index.vue;export default ZButton2、button 使用组件
我们在 home 页面导入组件来进行测试
script setup langts
import { useRouter } from vue-router
import useUserStore from /store/modules/user
import ZButton from /components/Button/index // 新增const router useRouter()
const userStore useUserStore()function goRouter(path: string): void {router.push(path)
}function getUserInfo(): void {console.log(userStore.userInfo, userStore.userInfo)
}
/scripttemplatediv classflex-c flex-align h-100el-button typeprimary clickgoRouter(/news)go news/el-buttonel-button typeprimary clickgoRouter(/user)go user/el-buttonel-button clickgetUserInfoget user info/el-buttonel-button typeprimary clickgoRouter(/table)go table/el-button!-- 新增 --z-button typeblue text测试blue :left10/z-button!-- 新增 --z-button typewarn text测试warn :left10/z-button/div
/template3、button 效果图 二、基于 Element-Plus 封装组件
1、table 代码 在 components 文件夹下创建 Table 文件。 在Table 文件中创建 index.vue 、 index.ts 和 types.ts 文件并编写以下代码 在 index.vue 文件中编写以下代码 script setup langts nameZTable
import { ref, computed, watch, nextTick, defineExpose } from vue
import { ElTable } from element-plus
import { ZTableOptions } from ./typesconst props withDefaults(defineProps{// 表格配置选项propList: ZTableOptions[]// 表格数据data: any[]// 表格高度height?: string | numbermaxHeight?: string | number// 显示复选框showSelectColumn?: boolean// 显示复选框showExpand?: boolean// 显示序号showIndexColumn?: boolean// 显示操作columnoperation?: boolean// 操作column 宽度operationWidth?: stringmoreOperationsPopoverWidth?: string// 加载状态loading?: boolean// 加载文案loadingText?: string// 加载图标名elementLoadingSpinner?: string// 是否显示分页pagination?: boolean// 显示分页的对齐方式paginationAlign?: left | center | rightpageInfo?: any// 显示分页数据多少条的选项pageSizes?: number[]// 数据总条数total?: numberemptyImg?: boolean}(),{propList: () [],height: 100%,operation: true,operationWidth: 240px,moreOperationsPopoverWidth: 160px,paginationAlign: right,pageInfo: () ({ page: 1, size: 10 }),pageSizes: () [10, 15, 20, 30],total: 0,emptyImg: true}
)const ZTableRef refInstanceTypetypeof ElTable()
const tablePropList: any ref([])watch(() props.propList,(list) {tablePropList.value []nextTick(() {tablePropList.value JSON.parse(JSON.stringify(list))})},{immediate: true}
)// 表格分页的排列方式
const justifyContent computed(() {if (props.paginationAlign left) return flex-startelse if (props.paginationAlign right) return flex-endelse return center
})const emits defineEmits([row-click,select-rows,page-change,sort-change,operation-click
])const handleOperationClick (row: any, code: string, index: number) {emits(operation-click, code, row, index)
}
const selectable (row: any, index: any) {return !row.noSelectable
}
const handleRowClick (row: any, column: any) {if (column?.label 操作) returnemits(row-click, row, column)
}
const handleSelectionChange (list: any) {emits(select-rows, list)
}
const handleSizeChange (size: number) {emits(page-change, { page: 1, size })
}
const handleCurrentChange (page: number) {emits(page-change, { ...props.pageInfo, page })
}
const changeTableSort (value: any) {emits(sort-change, value)
}
const toggleSelection (rows?: any) {if (rows) {rows.forEach((row: any) {ZTableRef.value!.toggleRowSelection(row, true)})} else {ZTableRef.value!.clearSelection()}
}defineExpose({toggleSelection
})
/scripttemplatediv classz-tableel-table :datadata :heightheight :max-heightmaxHeight refZTableRef v-loadingloading:element-loading-textloadingText :element-loading-spinnerelementLoadingSpinner stripesort-changechangeTableSort row-clickhandleRowClick selection-changehandleSelectionChangev-bind$attrstemplate #empty v-ifemptyImgdiv classempty-boxel-empty/el-empty/div/templateel-table-column typeexpand v-ifshowExpandtemplate #defaultscopeslot namebaseExpandSlot :rowscope.row/slot/template/el-table-columnel-table-column v-ifshowSelectColumn typeselection :selectableselectable fixedleft aligncenterwidth55/el-table-columnel-table-column v-ifshowIndexColumn fixedleft typeindex label序号 aligncenterwidth55/el-table-columntemplate v-forpropItem in tablePropList :keypropItem.proptemplate v-ifpropItem.visible ! falsetemplate v-if!propItem.slotNameel-table-column v-bindpropItem/el-table-column/templatetemplate v-elseel-table-column v-bindpropItemtemplate #defaultscopeslot :namepropItem.slotName :formatpropItem.dateFormat :rowscope.row :proppropItem.prop:indexscope.$index/slot/template/el-table-column/template/template/templateel-table-column v-ifoperation label操作 :widthoperationWidth fixedrighttemplate #defaultscopetemplate v-ifscope.row.operationsdiv classoperations-wraptemplate v-for(o, i) in scope.row.operations :keyo.codeel-button v-ifi 3 text typeprimary sizesmall :disabledo.disabledclickhandleOperationClick(scope.row, o.code, scope.$index){{ o.name }}/el-button/templateel-popover placementbottom-end :widthmoreOperationsPopoverWidthv-ifscope.row.operations.length 3template #referenceel-icon color#26A5FF classmore-dotMoreFilled //el-icon/templatediv classmore-operationstemplate v-for(o, i) in scope.row.operations :keyo.codeel-button v-ifi 2 text typeprimary sizesmall :disabledo.disabled clickhandleOperationClick(scope.row, o.code, scope.$index){{ o.name }}/el-button/template/div/el-popover/div/template/template/el-table-column/el-tablediv v-ifpagination classpagination :style{ justifyContent }el-pagination small :current-pagepageInfo.page :page-sizespageSizes :page-sizepageInfo.sizelayouttotal, sizes, prev, pager, next, jumper :totaltotal size-changehandleSizeChangecurrent-changehandleCurrentChange/el-pagination/div/div
/templatestyle langscss scoped
.operations-wrap {.el-button.el-button {margin-left: 25px;}.more-dot {position: relative;top: 0.3em;margin-left: 25px;font-size: 20px;cursor: pointer;}
}.more-operations {display: flex;flex-wrap: wrap;.el-button {overflow: hidden;margin-left: 10px;height: 32px;border-radius: 8px;line-height: 32px;}
}.el-loading-mask {z-index: 1;
}.pagination {display: flex;margin-top: 16px;
}.el-table__expand-column .cell {width: 55px;
}.is-dark {max-width: 40%;
}
/style在 index.ts 文件中编写以下代码 import ZTable from ./index.vueexport default ZTable在 types.ts 文件中编写以下代码 export interface ZTableOptions {// 是否可见visible?: boolean// 自定义列模板的插槽名slotName?: string// 日期格式化dateFormat?: string// 表头label: string// 字段名称prop?: string// 对应列的宽度width?: string | numberminWidth?: string | number// 对齐方式align?: left | center | rightfixed?: true | left | rightshowOverflowTooltip?: booleansortable?: boolean | custom
}2、table 组件使用 在 table 文件中下添加 index.vue 并添加对应路由文件编写以下代码 script langts setup
import ZTable from /components/Table/index
import { ref } from vue
import { ZTableOptions } from /components/Table/typesconst tableData: any ref([{fileName: 测试文件01,fileType: pdf,submitterName: 张三,submitTime: 2024-01-04 09:34:18},{fileName: 测试文件02,fileType: png,submitterName: 李四,submitTime: 2024-01-04 11:26:57}
])const propList: ZTableOptions[] [{showOverflowTooltip: true,label: 文件名称,prop: fileName,minWidth: 130,align: left},{showOverflowTooltip: true,label: 文件类型,prop: fileType,minWidth: 130,align: left},{label: 上传人,prop: submitterName,minWidth: 150,showOverflowTooltip: true},{label: 上传时间,prop: submitTime,minWidth: 160}
]
/scripttemplatedivz-table :propListpropList :datatableData :operationfalse/z-table/div
/templatestyle scoped langscss
/style3、table 效果图 总结
通过以上的介绍和代码实例我们可以看到 Vue3 提供了更多的特性和优化让我们更加方便地开发业务组件。在实际开发中我们可以根据实际需求选择合适的组件开发方式并通过 Vue3 的特性来提升开发效率。希望本文能够帮助到你在 Vue3 开发中的业务组件开发。上文中的配置代码可在 github 仓库中直接 copy仓库路径https://github.com/SmallTeddy/ProjectConstructionHub。