今天遇到了一個需求:點擊Switch更改音頻是否打開各薇,我需要在設(shè)置請求響應(yīng)之后再改變Switch的狀態(tài)遇汞。于是自己把el-switch組件進行了二次封裝撒遣。
<template>
<el-switch
:value="_value"
@change="onChange"
v-bind="$attrs"
:activeValue="activeValue"
:inactiveValue="inactiveValue"
>
</el-switch>
</template>
重新綁定value值载城,和change事件最铁,其余參數(shù)使用attrs 可以收集父組件中的所有傳過來的屬性除了那些在子組件中通過 props 定義的。
type valueType = string | number | boolean;
type fnType = (arg: valueType) => Promise<boolean>;
props: {
activeValue: {
type: [String, Number, Boolean],
default: true,
},
inactiveValue: {
type: [String, Number, Boolean],
default: false,
},
beforeChange: {
type: Function as PropType<fnType>,
},
value: {
type: [String, Number, Boolean],
default: false,
},
},
props定義父組件傳入的屬性
data() {
return {
_value: '' as valueType,
};
},
created() {
this._value = this.value; // 將父組件傳入的value值賦值給子組件
},
watch: {
value: function(v) {
this._value = v;
},
},
監(jiān)聽父組件傳入的value值垮兑,并賦值給子組件
onChange(changeVal: valueType) {
// 定義一個變量存儲改變之前的值
let beforeVal: valueType;
// 保存狀態(tài)改變之前的值
if (this.activeValue !== '' && this.inactiveValue !== '') {
beforeVal =
changeVal === this.activeValue
? this.inactiveValue
: this.activeValue;
} else {
beforeVal = !changeVal;
}
if (this.beforeChange != null) {
// 傳入組件changeVal
this.beforeChange(changeVal)
.catch(() => {
changeVal = beforeVal;
})
.finally(() => {
// 請求不管成功還是失敗最終會進到這里冷尉,成功時changeVal值不變,失敗時修改為改變之前的值
this._value = changeVal;
this.$emit('change', changeVal);
// 拋出input事件系枪,修改視圖
this.$emit('input', changeVal);
});
}
},
父組件的beforeChange方法雀哨,返回一個Promise,成功狀態(tài)為修改switch狀態(tài)私爷,失敗則為修改前的狀態(tài)
setAduioState(state: boolean): Promise<boolean> {
return new Promise((reslove, reject) => {
// 定時器設(shè)置禁用雾棺,防止頻繁點擊
setTimeout(() => {
this.audioDisabled = false;
}, 2000);
if (!this.audioDisabled) {
request
.serve({
method: 'post',
url: '/setAudioSwitch',
data: qs.stringify({ state: state }),
})
.then((res: any) => {
if (res.errorCode === 200) {
reslove(true);
} else {
// 拋出異常
throw new Error('設(shè)置錯誤');
}
})
.catch(() => {
reject(false);
});
}
this.audioDisabled = true;
});
},