- 代码复用:这个组件可以在多个页面或组件中使用,避免了重复编写相同的按钮代码。
- 灵活性:通过
showButtons
属性,可以根据需要显示不同的按钮。默认情况下,它会显示添加、修改和删除按钮,但你也可以根据具体情况传递其他值来显示或隐藏按钮。 - 可定制性:每个按钮都有自己的点击事件处理函数,你可以根据需要自定义这些函数的实现。
<template>
<el-button v-show="showButtons.includes('add')" type="primary" @click="handleAdd">添加</el-button>
<el-button v-show="showButtons.includes('update')" type="success" @click="handleUpdate">修改</el-button>
<el-button v-show="showButtons.includes('delete')" type="warning" @click="handleDelete">删除</el-button>
<el-button v-show="showButtons.includes('resource')" type="primary" @click="handleDelete">关联资源</el-button>
</template>
<script>
export default {
name: "CommonCrudButton",
props:{
showButtons:{
type:Array,
required:true,
default:['add','update','delete']
}
},
setup(props,{emit}){
console.log('curd button props',props.showButtons)
function handleAdd(){
emit('add')
}
function handleUpdate(){
emit('update')
}
function handleDelete(){
emit('delete')
}
return{handleDelete,handleUpdate,handleAdd}
}
}
</script>
<style scoped>
</style>
效果展示:
调用方法:
- 首先,确保你已经在项目中引入了Vue.js和Element UI库(因为代码中使用了Element UI的按钮组件)。
- 在需要使用这个组件的地方,导入它:
import CommonCrudButton from '@/components/CommonCrudButton.vue';
- 在你的Vue组件中,注册并使用组件。你可以通过CommonCrudButton v-show指令来控制按钮的显示与隐藏,以及通过@click监听按钮的点击事件:
<template>
<div>
<!-- 其他组件内容 -->
<CommonCrudButton :showButtons="['add', 'update', 'delete']" @add="handleAdd" @update="handleUpdate" @delete="handleDelete" />
</div>
</template>
<script>
import CommonCrudButton from '@/components/CommonCrudButton.vue';
export default {
components: {
CommonCrudButton,
},
methods: {
handleAdd() {
// 处理添加按钮点击事件
},
handleUpdate() {
// 处理修改按钮点击事件
},
handleDelete() {
// 处理删除按钮点击事件
},
},
};
</script>
复制
在methods
中实现按钮点击事件的处理逻辑,根据需要进行相应的操作。
这样,你就可以在你的Vue组件中使用这个通用的增删改查按钮组件了。根据传入的showButtons
属性值,它会显示相应的按钮,并在点击按钮时触发相应的事件处理函数。
转载自:vue通用的增删改查按钮组件