本文来源gaodai$ma#com搞$$代**码网
在组件实例中,Vue提供了相应的属性,包括$parent、$children、$refs和$root,这些属性都挂载在组件的this上。本文将详细介绍Vue组件实例间的直接访问,需要的朋友可以参考下
前面的话
有时候需要父组件访问子组件,子组件访问父组件,或者是子组件访问根组件。 在组件实例中,Vue提供了相应的属性,包括$parent、$children、$refs和$root,这些属性都挂载在组件的this上。本文将详细介绍Vue组件实例间的直接访问
$parent
$parent表示父组件的实例,该属性只读
下面是一个简易实例
<div id="example"> </div> <div class="parent"> <h3>我是父组件</h3><p>{{parentMsg}}</p></div> <div class="child"> <h3>我是子组件</h3><p>{{msg}}</p><button>显示父组件数据</button></div>
$root
$root表示当前组件树的根 Vue 实例。如果当前实例没有父实例,此实例将会是其自己。该属性只读
<div id="example"> <h3>我是根组件</h3><p>{{rootMsg}}</p></div> <div class="parent"> <h3>我是父组件</h3><p>{{parentMsg}}</p></div> <div class="child"> <h3>我是子组件</h3><p> <button>显示根组件数据</button><span>{{rootMsg}}</span></p><p> <button>显示父组件数据</button><span>{{parentMsg}}</span></p></div>
$children
$children表示当前实例的直接子组件。需要注意$children并不保证顺序,也不是响应式的。如果正在尝试使用$children来进行数据绑定,考虑使用一个数组配合v-for来生成子组件,并且使用Array作为真正的来源
<div id="example"> </div> <div class="parent"> <h3>我是父组件</h3><button>获取子组件数据</button><br><div></div></div> <div class="child"> <h3>我是子组件1</h3><p>{{msg}}</p></div> <div class="child"> <h3>我是子组件2</h3><p>{{msg}}</p></div>
$refs
组件个数较多时,难以记住各个组件的顺序和位置,通过序号访问子组件不是很方便
在子组件上使用ref属性,可以给子组件指定一个索引ID:
在父组件中,则通过$refs.索引ID访问子组件的实例
this.$refs.c1
this.$refs.c2
<div id="example"> </div> <div class="parent"> <h3>我是父组件</h3><div> <button>获取子组件c1的数据</button><p>{{msg1}}</p></div><div> <button>获取子组件c2的数据</button><p>{{msg2}}</p></div></div> <div class="child"> <h3>我是子组件1</h3><p>{{msg}}</p></div> <div class="child"> <h3>我是子组件2</h3><p>{{msg}}</p></div>
总结
虽然vue提供了以上方式对组件实例进行直接访问,但并不推荐这么做。这会导致组件间紧密耦合,且自身状态难以理解,所以尽量使用props、自定义事件以及内容分发slot来传递数据。
以上就是Vue组件实例间的直接访问实现代码的详细内容,更多请关注gaodaima搞代码网其它相关文章!