看此篇前,请阅读上一篇juejin.cn/post/691647…
在上一篇中, 我们用一个简单的 autoLoading属性 二次封装了el-button得到了pl-button组件,本篇中,我们继续丰富pl-button组件.
和自动loading相似,我们经常会有点击按钮需要弹窗二次确认的情况,如:点击删除按钮时,我们需要使用messageBox组件进行二次确认
this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
this.$message({
type: 'success',
message: '删除成功!'
});
}).catch(() => {
this.$message({
type: 'info',
message: '已取消删除'
});
});
如上代码,这种场景是非常多的,虽然仅仅就是一个确认,但每处都写,实属麻烦,重复代码过多,如果能够点击button自动二次确认, 用户二次点击确认才交给业务组件处理就方便多了. 这时我们可以想到, 在上一篇中, 我们点击了按钮之后,自己写了一段操作loading的代码,然后再将click事件emit出去, 这里我们同样可以这样做.
<el-button
v-bind="$attrs"
@click="handleClick"
>
<slot/>
</el-button>
<script>
export default {
name: 'pl-button',
props: {
autoConfirm: {
type: Boolean,
default: false
},
confirmConfig:{
type:Object,
default:()=>({})
}
},
methods: {
handleClick() {
if (this.autoConfirm) {
const {
message = '此操作将永久删除该数据, 是否继续?',
title = '提示',
confirmButtonText = '确定',
cancelButtonText = '取消',
type = 'warning'
} = this.confirmConfig
this.$confirm(message, title, {
confirmButtonText,
cancelButtonText,
type
})
.then(() => {
this.$emit('confirm')
})
.catch(() => {
this.$emit('cancel')
})
}else{
this.$emit('click')
}
}
}
}
</script>
在上述代码中,我们定义了一个autoConfirm的props属性, 如果此属性为true,那么点击按钮之后, 会自动调用this.$message.confirm进行二次确认,二次确认后,会emit('confirm')事件供业务组件调用. 使用方法如下:
<template>
<pl-button auto-confirm @confirm="handleConfirm">点击自动二次确认</pl-button>
</template>
<script>
export default{
methods:{
handleConfirm(){
// 这里是二次确认后执行
}
}
}
</script>
上面的使用代码非常简单, 我们只需要传递 auto-confirm属性,组件就能自动二次确认了, 二次确认后 使用confirm事件就能执行二次确认的事件了,这个小例子,却能解决我们很多的重复代码问题,使用起来非常方便.
限于掘金不能方便的展示,你可以通过查看此文档查看效果www.noob6.com/pl-element/…
系列文章地址: