Recently, in the project, the parent component needs to obtain the verification result of the child component (form), which is sorted out as follows:
Although there are prop s and events, sometimes you still need to access the subcomponents directly in JavaScript. To do this, use ref to specify a reference ID for the subcomponent. Ref is used to register reference information for elements or subcomponents. The reference information will be registered on the $refs object of the parent component. If it is used on a normal DOM element, the reference points to the DOM element; if it is used on a subcomponent, the reference points to the component instance. In this way, the child component method can be invoked in the parent component.
Sub components
<template>
<div>
<el-form :model="aForm" :rules="aRules" ref="aForm">
<el-form-item label="Name" prop="name">
<el-input v-model="aForm.name"></el-input>
</el-form-item>
<el-form-item label="Age" prop="age">
<el-input v-model="aForm.age"></el-input>
</el-form-item>
</el-form>
</div>
</template>
<script>
export default {
name: 'A',
data() {
return {
aForm: {
name: '',
age: ''
},
aRules: {
name: [
{ required: true, message: 'Please enter a name', trigger: 'blur' },
{ min: 3, max: 5, message: '3 to 5 characters in length', trigger: 'blur' }
],
age: [
{ required: true, message: 'Please enter age', trigger: 'blur' }
],
}
}
},
methods: {
validateForm() {
let flag = false
this.$refs['aForm'].validate((valid) => {
flag = valid
})
return flag
}
}
}
</script>
Parent component
<template>
<div>
<A ref="a"></A>
<el-button @click="save">Preservation</el-button>
</div>
</template>
<script>
import A from './a.vue'
export default {
name: 'child-component-validate',
data() {
return {}
},
methods: {
save() {
console.log(this.$refs['a'].validateForm())
}
},
components: {
A
}
}
</script>
When v-for is used for an element or component, the reference information will be an array containing DOM nodes or component instances.
Important note about ref registration time: because refs are created as rendering results, you cannot access them at the time of initial rendering - they do not exist yet! $refs is not reactive either, so you shouldn't try to use it as a data binding in a template.