设置 beforeChange 属性,若返回 false 或者返回 Promise 且被 reject,则停止切换。
<el-switch v-model="value1" :loading="loading1" :before-change="beforeChange1" />const value1 = ref(false)
const loading1 = ref(false)const beforeChange1 = () => {
loading1.value = true
return new Promise((resolve) => { setTimeout(() => { loading1.value = false ElMessage.success('Switch success') return resolve(true) }, 1000)
})
}
表格中的switch根据此行的某些数据,判断是否阻止切换
<el-table-column align="center" label="开关" prop="switch_status"><template #default="scope"><el-switchv-model="scope.row.switch_status"inline-promptactive-text="正常"inactive-text="异常":active-value="1":loading="loading":inactive-value="0":before-change="() => beforeChange(scope.row)"@change="changeSwitch(scope.row, scope.$index)"/></template></el-table-column>const beforeChange = async (row) => {if(不需要阻止切换){return true}else{return false}
若是使用 @change,此时Switch状态已经被切换,若此时应该是禁止切换,再切换为原来的状态,则会出现切换的过程,一闪而过,用户视觉体验不好。