Developing Vue During the project , Custom component of code reuse is often done . When the subcomponent is form Form time , The parent component needs to get the child component ( Forms ) The verification results of the .
Although there are prop And events , But sometimes it still needs to be in JavaScript Direct access to sub components in . You can use ref Specify a reference for the child component ID.ref Used to register reference information for an element or subcomponent . The reference information will be registered in the $refs On the object . If in the ordinary DOM Use on element , The reference points to DOM Elements ; If it is used on sub components , References point to component instances . In this way , You can invoke the child component method in the parent component !
Child 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 name ', trigger: 'blur' },
{ min: 3, max: 5, message: ' The length is in 3 To 5 Characters ', 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 When it comes to elements or components , The reference will contain DOM An array of nodes or component instances .
About ref Important note on registration time : because ref Itself is created as a result of rendering , You can't access them during the initial rendering - They don't exist yet !$refs It's not reactive either , So you shouldn't try to use it for data binding in templates .