element-ui Switch组件,在@change前添加确认框?确认后改变值,取消不改变
先说说思路
利用组件的继承功能(extends),重写handleChange方法,同时不影响其他地方已经使用的
具体操作方法?
1.新建一个js文件,在main.js中引入
// 文件名字自己定义
import patch from '@/components/patch.js'
Vue.use(patch);
2.patch.js具体内容
import {Switch } from "element-ui";
const switchPatch = {
extends:Switch, // 继承switch组件
props:{
// 传入的beforechange方法
handleBeforeChange:Function
},
methods:{
async handleChange(event){
// 判断是否存在handleBeforeChange方法
// 使用Promise来处理
if(this.handleBeforeChange){
const before = await this.handleBeforeChange(event)
if(before === false){
return
}
}
// 这是源码部分,直接复制过来即可
const val = this.checked ? this.inactiveValue : this.activeValue;
this.$emit('input', val);
this.$emit('change', val);
this.$nextTick(() => {
// set input's checked property
// in case parent refuses to change component's value
if (this.$refs.input) {
this.$refs.input.checked = this.checked;
}
});
}
}
}
export default{
install(Vue){
// 重新定义switch组件,使用我们自己的模板switchPatch
Vue.component('el-switch',switchPatch);
}
}
3.具体使用
传入handleBeforeChange到组件
<el-switch
v-model="value"
// 传入到组件的方法
:handleBeforeChange="handleBeforeChange"
active-color="#13ce66"
inactive-color="#ff4949">
</el-switch>
定义handleBeforeChange方法
methods: {
handleBeforeChange(){
return new Promise(resolve=>{
this.$confirm('确认是否改变').then(()=>{
resolve(true)
}).catch(()=>{
resolve(false)
})
})
},
}
4.具体的效果
注:select组件如何要添加弹框,也是同样的思路处理思路