vue2 $ref, $parent, $children的使用
父子组件之间的通信一直是vue里面比较常用的功能点,在父子组件的实例中有 $ref, $parent, $children 三个常用的属性。
$ref
作用:获取对应组件实例,获取后可以使用组件实例上的方法和属性
<template>
<my-component ref="mcRef"></my-component>
</template>
<script>
export default {
update() {
// 因为 this.$ref.mcRef 获取的属性和方法需要组件实例完全更新好后才能拿到,所以放到update中
// 如果需要放到 mounted 或者 methods 中,则可以配合 this.$nextTick 函数进行使用
console.log(this.$refs.mcRef)
}
}
</script>
$parent
作用:可以在子组件的使用区域,通过 this.$parent 获取父组件的实例,从而使用父组件实例上的方法和属性。
父组件文件
<template>
<a></a>
</template>
<script>
// 注册组件的步骤就省略了哈
export default {
data() {
return {
msg: '这是一个父组件变量'
}
}
}
</script>
子组件文件 a.vue
<template>
<son-component @clcik="changeParentprops"></son-component>
</template>
<script>
export default {
methods: {
changeParentprops() {
this.$parent.msg = '子组件修改了父组件的变量'
}
}
}
</script>
注意:子组件如果被多个父组件调用,虽然会针对每一个调用创建一个独立的实例,但通过this.$parent使用的方法和属性的影响会作用到每一个调用该子组件的父组件实例上。
$children
作用:在父组件的使用区域内,通过 this.$childen 获取子组件的实例数组,从而通过数组使用每个子组件实例的属性和方法。
<template>
<a></a>
<b></b>
</template>
<script>
export default {
update() {
console.log(this.$children[0]) //获取a子组件实例
console.log(this.$children[1]) //获取b子组件实例
}
}
</script>