Vue组件化之父子组件的相互访问

父访问子 children-refs

当父组件想直接调用子组件的数据或方法时。

父组件访问子组件:使用$children或 $refs

children

在父组件中调用this.$children会返回包含子组件对象的数组,用索引找到对应的子组件

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

父组件中调用this.$refs会返回{ref:VueComponent}的对象,用命名找到对应的子组件

<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的子组件
    }
}

子访问父 parent-root

子组件访问父组件:使用 p a r e n t ( 仅 上 一 级 的 父 组 件 ) 用 法 与 parent (仅上一级的父组件) 用法与 parent()children相似

子组件访问根组件:使用 r o o t ( 返 回 到 最 外 层 的 组 件 , 可 能 是 V u e 实 例 ) t h i s . root (返回到最外层的组件,可能是Vue实例) this. rootVuethis.root.message

猜你喜欢

转载自blog.csdn.net/Pinoochio/article/details/113328086