Mutual access between parent and child components of Vue componentization

Parent visits child children-refs

When the parent component wants to directly call the data or method of the child component.

Parent component to access child components: use $children or $refs

children

Calling this.$children in the parent component will return an array containing child component objects, and use the index to find the corresponding child component

父组件methods:{
    
    
    btnclick(){
    
    
		this.$children[0].showMessage()   //即可调用索引为0的子组件中的showMessage方法
    }
}
ref

Calling this.$refs in the parent component will return the object of {ref:VueComponent}, and find the corresponding child component by name

<div id="app">
    <cpn ref='aaa'></cpn>
	<cpn ref='bbb'></cpn>
	<cpn></cpn>
</div>
父组件methods:{
    
    
    btnclick(){
    
    
		console.log(this.refs)  //返回所有带ref的子组件对象
        console.log(this.refs.aaa)  //返回ref为aaa的子组件
    }
}

Child access parent parent-root

Child component access parent component: use parent (only the parent component of the upper level) usage and parent (only the parent component of the upper level) usage andP A R & lt E n- T ( only on a stage of the parent group member ) by methods and children is similar to

Sub-component access to the root component: use root (return to the outermost component, which may be a V ue instance) this. root (return to the outermost component, which may be a Vue instance) this.R & lt O O T ( returned back to the most outer layer of the group member , may be able to be V U E solid embodiment ) T H I S . root.message

Guess you like

Origin blog.csdn.net/Pinoochio/article/details/113328086