Summary of application of elementui form checking in large projects
Use of vuex
- In the vue+elementui project, you can use vuex for state data management, which you can see here: Introduction to vuex
Validation of forms in elemenuit
- First, you need to know the basic example of form validation: here: Form form for elementui
- Next, there are some particularly important points to note when writing a form: you can see here: Form Check Notes for elementui
- In a large project, a large data storage, data will certainly exist in many sub-components, when you click Save, how can you detect all the form elements?Writing in one form is definitely not possible.
summary
- Store data in different vue subcomponents (or store shares), store refs in each subcomponent in a shared data store, wrap a form el-form outside each subcomponent, and define unique ref attributes. Writable save methods are available in the parent component invoked by these subcomponents
- Code
//Parent Component
<template>
<div>
<child1></child1>
<child2></child2>
<child3></child3>
<el-button @click="save'>Preservation</el-button>
</div>
</template>
<script>
import child1 from '@/components/child1'
import child2 from '@/components/child2'
import child3 from '@/components/child3'
export default {
components: {
child1,
child2,
child3,
},
data(){
return {}
},
methods: {
save() {
console.log(this.$store.state.refs)
//Loop through the data for each form in refs
let refs = this.$store.state.refs
let ok = 0
for(let k in refs ) {
let el = refs[k]
if(el.validate) {
el.validate(valid => {
if(k==="child1"){
if(!valid) {
alert('child1 Information not completed')
}
}
if(valid) ok++
return valid
})
}
}
if(ok !== 3) return
//Continue with other content
}
}
}
</script>
//Subcomponents
<template>
<div>
<el-form :model="data" :rules="ruleForm" ref="child1">
<el-row :gutter="20">
<el-col :span="10">
<el-form-item label="Full name" prop="name">
<el-input v-model="data.name"></el-input>
</el-form-item>
</el-col>
</el-row>
</el-form>
</div>
</template>
<script>
export default {
data() {
return {
data: {
name: ''
},
ruleForm: {
name: [{required: true, message:'Required Information',trigger:'input'}]
}
}
},
mounted() {
this.$store.state.refs.child1 = this.$refs.child1
}
}
</script>