我有这两个条件
if (civility.labelKey === lady) {
const contactType = this.contactTypes.find((type) => type.label_key === madam)
this.onSelect({
$event: { contactType }
})
this.contact.greetings = civility
} else {
const contactType = this.contactTypes.find((type) => type.label_key === civility.labelKey)
this.onSelect({
$event: { contactType }
})
}
我想分解(统一)这段代码:
this.onSelect({
$event: { contactType }
})
谁重复两次,你有解决方案吗?
答案 0 :(得分:1)
你可以提取这样的函数:
function bindOnSelect(component, contactType){
component.onSelect({
$event: { contactType }
})
}
然后调用该函数:
if (civility.labelKey === lady) {
const contactType = this.contactTypes.find((type) => type.label_key === madam)
bindOnSelect(this, contactType);
this.contact.greetings = civility
} else {
const contactType = this.contactTypes.find((type) => type.label_key === civility.labelKey)
bindOnSelect(this, contactType);
}