为了实现父子组件之间的访问,即父组件访问子组件中的方法与属性,子组件访问父组件的方法与属性,使用以下操作实现父子组件之间的访问。
$children
使用$children来实现父组件访问子组件,返回结果为VueComponent,数组类型。
当访问子组件的属性时,需要添加第几个组件的属性。
console.log(this.$children);
console.log(this.$children[0].name);
$refs
当有多个子组件时,想要获取某个特定的子组件的值时,需要使用$refs来实现。
在父组件中调用子组件时添加ref属性之后,便可以使用 $refs.ref属性值来获取到该子组件的属性以及方法。
<div id="app">
<cpn></cpn>
<cpn ref="rcpn"></cpn>
<cpn></cpn>
<cpn></cpn>
<button @click="show">父组件访问某个特定的子组件</button>
</div>
console.log(this.$refs.rcpn);
console.log(this.$refs.rcpn.name);
$parent
使用$parent来访问父组件中的属性以及方法,与 $children类似。使用 $parent只能访问当前子组件的上一层父组件,无法访问父组件的父组件。
$root
在子组件中访问根组件的属性与方法,与 $children类似。