Vue 组件通信方式$refs/ $parens /$children /$root
$refs:
通常会将$refs
绑定在DOM元素上,来获取DOM元素的attribute。在实现组件通信上,也可以将$refs
绑定在子组件上,从而获取子组件的实例。
$parens :
在Vue中风直接通过this.$parent
来获取当前组件的父组件实例。
$children :
同样的,也可以在Vue中直接通过this.$children
来获取当前组件的子组件实例。注意:this.$children
数组中的元素下标并不一定对用父组件引用的子组件的顺序。所以在使用时需要根据一定的条件例如子组件的name去找相应的子组件。
$root:
当前组件树的根Vue实例。如果当前实例没有父实例,此实例将会是其自己。通过$root
,可以实现组件之间的跨级通信。
父向子传值:子组件通过$parent.msg
获取到父组件中message的值。
子向父传值:父组件通过$children获取子组件实例的数组,在通过对数组进行遍历,通过实例的 name 获取到对应 Child1 子组件实例将其赋值给 child1,然后通过child1.msg获取到 Child1 子组件的msg。
// 子组件
<template>
<div class="childbox">
<h4>这是子组件</h4>
<input type="text" v-model="msg" />
<p>收到来自父组件的消息:{{ $parent.msg}}</p>
</div>
</template>
<script>
export default {
name: 'Childs',
data() {
return {
msg: '',
}
},
}
</script>
// 父组件
<template>
<div class="parentbox">
<h3>这是父组件</h3>
<input type="text" v-model="msg" />
<p>收到来自子组件的消息:{{ child1.msg}}</p> <!--展示子组件实例的msg-->
<Childs />
</div>
</template>
<script>
import Childs from './childs'
export default {
name: 'Parent',
data() {
return {
msg: '',
child1: {},
}
},
components: {
Childs,
},
mounted() {
this.child1 = this.$children.find((child) => {
return child.$options.name === 'Childs' // 通过options.name获取对应name的childs实例
})
},
}
</script>