Vue2 elementui2 中 el-switch 实现先判断改变状态
Vue2 elementui2 中 el-switch 实现先判断改变状态
最后附上完整组件代码
elementui 中 el-switch在使用时,直接使用change 事件,每次点击 时都先改变switch 状态,然后再处理业务逻辑,体验上不优好。根据产品要求需要先处理业务逻辑再改变switch状态。
具体实现: 给switch组件设置disable (必须设置), 禁用掉操作,然后给switch 添加上@click.native 或 @click.native.prevent 事件
- 添加
@click.native.prevent方法达到目的,- 给vue组件绑定事件时候,必须加上
native,否则会认为监听的是来自Item组件自定义的事件 prevent是用来阻止默认的 ,相当于原生的event.preventDefault()
- 给vue组件绑定事件时候,必须加上
- 与此同时需要打开
disabled属性 - 是因为不加
disabled会出现调用两次的非理想状态
<el-table-column
label="渠道状态"
prop="state"
width="80">
<template slot-scope="{ row }">
<el-switch
v-model="row.state"
:active-value="1"
:inactive-value="2"
@click.native="handleSwitchange(row.state, row)"
disabled
/>
</template>
</el-table-column>handleSwitchange(e,row) {
const msg = e === 1 ? `确定关闭渠道 ${row.channelId}吗?` : `确定开启渠道 ${row.channelId}吗?`
this.$modal.confirm(msg).then(() => {
// 处理业务逻辑
row.state = e === 1 ?2:1
}).then(() => {
// 成功时执行
row.state = e === 1 ?2:1
}).catch(() => {
//取消或失败时处理
});
}最后修改switch 的 disabled样式问题
• 保证修改完后同样式正常无异
• 在设置disabled后开关会有鼠标禁用的样式及透明度的变化,需要我们做修改。 这里不建议直接在使用style 中修改避免污染其他界面样式,建议使用深度选择器deep进行修改
<style lang="scss" scoped>
/* 深度选择器进行样式穿透 */
::v-deep{
/* 修改elementUI-switch组件 disabled样式 */
.el-switch.is-disabled {
opacity: 1;
}
/*修改鼠标悬停显示状态*/
.el-switch.is-disabled .el-switch__core,
.el-switch.is-disabled .el-switch__label {
cursor: pointer !important; /*这里修改成小手状态*/
}
}
</style>不使用深度选择器,这里需要去掉scoped
<style lang="scss" >
/* 修改elementUI-switch组件 disabled样式 */
.el-switch.is-disabled {
opacity: 1;
}
/*修改鼠标悬停显示状态*/
.el-switch.is-disabled .el-switch__core,
.el-switch.is-disabled .el-switch__label {
cursor: pointer !important; /*这里修改成小手状态*/
}
</style>完整组件代码:
使用:
<switch-plus v-model="row.state" :active-value="1" :inactive-value="2" @onChange="handleSwitchange(row.state, row)" />
switchplus.vue:
<template>
<el-switch v-bind="$attrs" @click.native.prevent="$emit('onChange')" disabled />
</template>
<script>
export default {
name: 'SwitchPlus',
data() {
return {
}
},
mounted() {
},
methods: {
},
}
</script>
<style lang="scss" scoped>
//直接写类名(不带deep)
.el-switch.is-disabled {
opacity: 1 !important;
// 用 ::v-deep 包起来
::v-deep {
.el-switch__core , .el-switch__label{
pointer-events: auto !important;
cursor: pointer !important;
}
}
}
</style>到此这篇关于Vue2 elementui2 中 el-switch 实现先判断改变状态的文章就介绍到这了,更多相关Vue elementui el-switch判断改变状态内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!


最新评论