YOU编程__封装ElementPlus通用组件(会持续更新...)
1、通用表格组件
-
CommonTable.vue
<template><el-form :model="query" inline class="query-form"> <el-form-item> <el-input v-model="query.keyword" placeholder="请输入关键词"></el-input> </el-form-item> <el-form-item> <el-button type="primary" @click="handleQuery">查询</el-button> </el-form-item> <el-form-item> <el-button type="primary" @click="handleAdd">添加</el-button> </el-form-item> </el-form> <el-table :data="tableData" class="data-table"> <el-table-column v-for="column in columns" :key="column.prop" :prop="column.prop" :label="column.label"></el-table-column> <el-table-column label="操作"> <template v-slot="scope"> <el-button type="text" @click="handleEdit(scope.row)">修改</el-button> <el-button type="text" @click="handleDelete(scope.row)">删除</el-button> </template> </el-table-column> </el-table> <el-pagination background layout="prev, pager, next" :total="total" @current-change="handlePageChange" /></template> <script setup> import { ref, defineProps, defineEmits, watch } from 'vue' import { ElMessage } from 'element-plus'const props = defineProps({
columns: {
type: Array,
required: true
},
data: {
type: Array,
required: true
},
total: {
type: Number,
required: true
}
})const emits = defineEmits(['query', 'add', 'pageChange', 'edit', 'delete'])
const query = ref({
keyword: ''
})const tableData = ref(props.data)
const totalRecords = ref(props.total)watch(() => props.data, (newData) => {
tableData.value = newData
})const handleQuery = () => {
ElMessage.success('查询功能触发')
emits('query', query.value)
}const handleAdd = () => {
ElMessage.success('添加功能触发')
emits('add')
}const handleEdit = (row) => {
ElMessage.success('修改功能触发')
emits('edit', row)
}const handleDelete = (row) => {
ElMessage.success('删除功能触发')
emits('delete', row)
}const handlePageChange = (page) => {
<style> .query-form{ margin-top: 20px; } .data-table{ width: 100%; margin: 0px 0px 20px 0px; } </style>
ElMessage.success(当前页: ${page}
)
emits('pageChange', page)
}
</script> -
使用示例
<template><CommonTable :columns="columns" :data="tableData" :total="total" @query="handleQuery" @add="handleAdd" @edit="handleEdit" @delete="handleDelete" @pageChange="handlePageChange" /></template> <script setup> import { ref } from 'vue' import CommonTable from '@/components/CommonTable.vue'const columns = ref([
{ prop: 'name', label: '名称' },
{ prop: 'age', label: '年龄' },
{ prop: 'address', label: '地址' }
])const tableData = ref([
{ name: 'John Doe', age: 30, address: 'New York' },
{ name: 'Jane Doe', age: 25, address: 'Los Angeles' }
])const total = ref(50) // 假设总记录数为50
const handleQuery = (query) => {
console.log('查询条件:', query)
// 在这里添加查询逻辑
}const handleAdd = () => {
console.log('触发添加功能')
// 在这里添加添加逻辑
}const handleEdit = (row) => {
console.log('修改行:', row)
// 在这里添加修改逻辑
}const handleDelete = (row) => {
console.log('删除行:', row)
// 在这里添加删除逻辑
}const handlePageChange = (page) => {
console.log('当前页:', page)
// 在这里添加分页逻辑
}
</script>