后台开发经常会涉及到新增、编辑操作。通常在新增时需要把表单元素的值初始化,vue+element ui开发如果用element ui的form表单验证this.$refs[formName].validate()来实现,可以用this.$refs[formName].resetFields()实现初始化。
但是表单验证不能完全满足开发的需要,比如:验证图片是否上传,验证表格里是否至少包含一行数据等非表单元素时有缺陷。
所以当不使用validate()方法时,如何实现表单元素初始化?以下举例说明问题:
<html>
<head></head>
<body>
<script type="text/javascript">
console.log('--------------------当赋值都为空字符串时------------------------')
let addForm = {
id: '',
name: '',
feeType: '',
summary: '',
content: '',
showTimeRange: '',
activeTimeRange: '',
startTime: '',
endTime: '',
type: '',
total: '',
age: '',
graduate: ''
}
console.time('forEach方法')
Object.keys(addForm).forEach((key, i) => {
addForm[key] = ''
})
console.timeEnd('forEach方法')
console.time('forin循环')
for (let i in addForm) {
addForm[i] = ''
}
console.timeEnd('forin循环')
console.time('直接赋值')
addForm = {
id: '',
name: '',
feeType: '',
summary: '',
content: '',
showTimeRange: '',
activeTimeRange: '',
startTime: '',
endTime: '',
type: '',
total: '',
age: '',
graduate: ''
}
console.timeEnd('直接赋值')
console.log('---------------------当赋值含有初始值时-----------------------')
let addForm1 = {
id: '',
name: '',
feeType: 'init',
summary: '',
content: '',
showTimeRange: '',
activeTimeRange: '',
startTime: '',
endTime: '',
type: '1',
total: '',
age: '15',
graduate: ''
}
console.time('forEach方法')
Object.keys(addForm1).forEach((key, i) => {
switch (key) {
case 'type':
addForm1[key] = '1'
break
case 'feeType':
addForm1[key] = 'init'
break
case 'age':
addForm1[key] = '15'
break
default:
addForm1[key] = ''
}
})
console.timeEnd('forEach方法')
console.time('forin循环')
for (let i in addForm1) {
switch (i) {
case 'type':
addForm1[i] = '1'
break
case 'feeType':
addForm1[i] = 'init'
break
case 'age':
addForm1[i] = '15'
break
default:
addForm1[i] = ''
}
}
console.timeEnd('forin循环')
console.time('直接赋值')
addForm1 = {
id: '',
name: '',
feeType: 'init',
summary: '',
content: '',
showTimeRange: '',
activeTimeRange: '',
startTime: '',
endTime: '',
type: '1',
total: '',
age: '15',
graduate: ''
}
console.timeEnd('直接赋值')
</script>
</body>
</html>
执行结果:
从控制台中可以看到,forEach方法耗时,for in循环和直接赋值性能差不多,但是对于有初始值的元素来说,for in要做特殊处理,所以建议直接赋值。
大家有更好的想法,欢迎提出。