element-ui Switch组件,在change前添加确认框?确认后改变值,取消不改变

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组件如何要添加弹框,也是同样的思路处理思路

  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值