Background development often involves new and edit operations. Usually, the value of the form element needs to be initialized when adding. If the form form of element ui is used to verify this.$refs[formName].validate(), then this.$refs[formName].resetFields() can be used for initialization.
However, form validation can not fully meet the needs of development. For example, there are defects in verifying whether the image is uploaded and whether the form contains at least one row of data and other non form elements.
So how to initialize form elements when the validate() method is not used? Here are some examples:
<html> <head></head> <body> <script type="text/javascript"> console.log('--------------------When all assignments are empty strings------------------------') let addForm = { id: '', name: '', feeType: '', summary: '', content: '', showTimeRange: '', activeTimeRange: '', startTime: '', endTime: '', type: '', total: '', age: '', graduate: '' } console.time('forEach Method') Object.keys(addForm).forEach((key, i) => { addForm[key] = '' }) console.timeEnd('forEach Method') console.time('forin loop') for (let i in addForm) { addForm[i] = '' } console.timeEnd('forin loop') console.time('Direct assignment') addForm = { id: '', name: '', feeType: '', summary: '', content: '', showTimeRange: '', activeTimeRange: '', startTime: '', endTime: '', type: '', total: '', age: '', graduate: '' } console.timeEnd('Direct assignment') console.log('---------------------When the assignment contains an initial value-----------------------') let addForm1 = { id: '', name: '', feeType: 'init', summary: '', content: '', showTimeRange: '', activeTimeRange: '', startTime: '', endTime: '', type: '1', total: '', age: '15', graduate: '' } console.time('forEach Method') 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 Method') console.time('forin loop') 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 loop') console.time('Direct assignment') addForm1 = { id: '', name: '', feeType: 'init', summary: '', content: '', showTimeRange: '', activeTimeRange: '', startTime: '', endTime: '', type: '1', total: '', age: '15', graduate: '' } console.timeEnd('Direct assignment') </script> </body> </html>
Execution result:
It can be seen from the console that forEach method takes time, and the performance of for in loop is similar to that of direct assignment. However, for in needs special processing for elements with initial values, so direct assignment is recommended.
You have better ideas, welcome to put forward.