起因
众所周知,对象支持[]写法的动态属性,我们可以在[]中写入变量或字符串,关于语法层面知识的不做赘述。可是有时候我们写函数,两个函数的结构差异较小,但函数没有动态属性名的写法,我们该怎么做呢?
具体情况
以Vue代码为例,比较一般的写法:
<button @click="addOne">新增</button>
<button @click="editOne(id)">编辑</button>
import { addOne, editOne } from '@/api/xxx'
export default {
methods: {
addOne() {
this.$loading.show()
addOne(this.form)
.then(res => {
this.$message({
message: '新增成功',
type: 'success'
})
})
.catch(err => {
this.$message.error(err)
})
.finally(() => {
this.$loading.hide()
})
},
editOne(id) { // 编辑一般会多id字段
this.$loading.show()
editOne({
...this.form,
id
})
.then(res => {
this.$message({
message: '编辑成功',
type: 'success'
})
})
.catch(err => {
this.$message.error(err)
})
.finally(() => {
this.$loading.hide()
})
}
}
}
可以看到,两个函数除了方法名和提示文案不一样之外,几乎一模一样,这种情况下,代码就冗余了。我们要提升方法的复用率,让自己少写代码,让代码更简洁精炼。有人说,那就用一个方法来写,插入if...else,我就不卖关子了,直接贴出来我的写法:
<button @click="handleOne">新增</button>
<button @click="handleOne(1, id)">编辑</button>
import { addOne, editOne } from '@/api/xxx'
export default {
methods: {
handleOne(type = 0, id) { // type: 0.新增 1.编辑
this.$loading.show()
const obj = {
addOne,
editOne
}
obj[type ? 'editOne' : 'addOne']({
...this.form,
...type && {id} // 只有编辑的时候,才传id字段
})
.then(res => {
this.$message({
message: `${type ? '编辑' : '新增'}成功`,
type: 'success'
})
})
.catch(err => {
this.$message.error(err)
})
.finally(() => {
this.$loading.hide()
})
}
}
}
上面就是我的写法,怎么样?是不是和你想的一样,总之代码复用率很高了。
详解
函数没有动态属性名的写法,只有对象有,那我们就用对象的呗。...type && {id}这行代码看不懂的,可以去看我的第一篇文章《理解:有条件的对象属性》,有条件的对象属性,可以帮我们做很多事。