父组件与子组件的关系
在Vue中,父组件可以通过 $refs来管理通过ref注册过的所有子组件,即 $refs对象下可以包含很多 $ref对象。
事件响应
分别定义两个组件 parent.vue 和 sub.vue
其中 parent.vue
//如果想要实际测试代码的话,请优先引入ant-desigin-vue
<template>
<div>
<a-button type="primary" @click="parentButtonClick">父组件事件分发按钮</a-button>
//将子组件声明为child ref对象
<subComponent ref="child"></subComponent>
</div>
</template>
<script>
import subComponent from './subComponent'
export default {
name: 'parent',
components: {
subComponent
},
methods: {
parentButtonClick () {
this.$refs.child.reciveParentMsg('点击父组件按钮发送的消息')
}
}
}
</script>
<style>
</style>
sub.vue
<template>
<p>从父组件接收到的消息为:{{reciveMsg}}</p>
</template>
<script>
export default {
data: function () {
return {
reciveMsg: ''
}
},
methods: {
reciveParentMsg (msg) {
this.reciveMsg = msg
}
}
}
</script>
<style>
</style>
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200519211016742.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzI3Nzk4Mzc1,size_16,color_FFFFFF,t_70)
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200519211026288.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzI3Nzk4Mzc1,size_16,color_FFFFFF,t_70)