The son said to his father: "Father! I drove your car today"
- The parent visits the child with $children
- The child visits the parent with $parent
- It is more recommended to use $refs for the parent to visit the child
- Because $children has a subscript value, once the structure changes, there is no way to dynamically change the subscript value. This method is not recommended
Father visits son
- Create a parent-child relationship first
<div id="father">
<h1>{
{
name}}</h1>
<button>我要调用我的儿子的方法</button>
<son></son>
</div>
<template id="son">
<div>
<h2>{
{
name}}</h2>
<h2>{
{
message}}</h2>
</div>
</template>
const son = {
template:'#son',
data() {
return {
name:'我是儿子',
message:''
}
},
methods:{
showMessage() {
console.log('我被我爹调用了')
this.message = '我被我爹调用了'
}
}
}
const father = new Vue({
el:'#father',
data:{
name:'我是爹'
},
components:{
son
}
})
Take a look at the page effect.
Clicking the button will call the showMessage method on the son.
- Imprint the son's label
- Bind events to the button
- ref and $refs are a pair, ref is used to mark tags
<div id="father">
<h1>{
{
name}}</h1>
<button @click="btnClick">我要调用我的儿子的方法</button>
<son ref='son'></son>
</div>
- $refs.son is used to select the label marked with son
- More precisely, which component (vueComponent instance)
const father = new Vue({
//。。。
methods:{
btnClick() {
console.log(this.$refs.son)
this.$refs.son.showMessage()
}
},
})
Take a look at the page effect
Son visits father
- $parent
- $root access to ancestors
- This is not recommended for actual development, because in this way, the sub-components are not independent enough, and the father of this sub-component is different in another place, and there may be no target attributes.
- Component development itself is to improve reusability, and the coupling between the parent component is too high
Add a data to dad for use by son
const father = new Vue({
el:'#father',
data:{
name:'我是爹',
fatherMes:'我将给我儿子'
},
//。。。。
})
Add a button to the son to click to call dad's data
<template id="son">
<div>
<h2>{
{
name}}</h2>
<h2>{
{
message}}</h2>
<button @click="callFather">调用我爹地数据</button>
</div>
</template>
Add event
const son = {
// 。。。。
methods:{
//。。。。
callFather() {
console.log(this.$parent)
console.log(this.$parent.fatherMes);
}
}
}
View page effect