Summary of the application of elementui form validation in large projects
The use of vuex
- In the vue+elementui project, vuex can be used for state data management, which can be viewed here: vuex introduction
Validation of forms in elemenuit
- First of all, you need to know the basic example of form validation: You can view it here: elementui's form form
- Secondly, pay attention to some particularly important points when writing forms: You can check here: Elementui's form validation points
- In a large-scale project, when a large data is saved, the data will definitely exist in many sub-components. How can all form elements be detected when saving is clicked? It's definitely not enough to just write it in one form.
Summarize
- Store data in different vue sub-components (or store sharing, either), store the refs in each sub-component in the shared data store, each sub-component needs to wrap a form el-form in the outer layer, and define The only ref attribute, then in the parent component called by these child components, the save method can be written
- code
//父组件
<template>
<div>
<child1></child1>
<child2></child2>
<child3></child3>
<el-button @click="save'>保存</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)
//循环判断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信息未填写完成')
}
}
if(valid) ok++
return valid
})
}
}
if(ok !== 3) return
//继续其他内容
}
}
}
</script>
//子组件
<template>
<div>
<el-form :model="data" :rules="ruleForm" ref="child1">
<el-row :gutter="20">
<el-col :span="10">
<el-form-item label="姓名" 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:'必填信息',trigger:'input'}]
}
}
},
mounted() {
this.$store.state.refs.child1 = this.$refs.child1
}
}
</script>