业务场景:(这里指的是直接父子级关系的通信)
- 美女(子组件)将消息发送给大群(父组件)
- 大群(父组件)收到美女发送的消息后再回个信息给美女(子组件)
父组件
template
群消息girl:
{{ somebody }} 说: 我 {{ age }} 了。
<v-girl-group
:girls="aGirls"
:noticeGirl="noticeGirl"
@introduce="introduceSelf"></v-girl-group>
注意的点:
- 这里在父组件使用v-on来监听子组件上的自定义事件($emit的变化),一旦发生变化noticeGirl方法就会触发
import vGirlGroup from './GirlGroup'
export default {
name: 'girl',components: {
vGirlGroup
},data () {
return {
aGirls:[{
name:'小丽',age:22
},{
name:'小美',age:21
},{
name:'小荷',age:24
}],somebody:'',age:'',noticeGirl:''
}
},methods: {
introduceSelf (opt) {
this.somebody = opt.name;
this.age = opt.age;
// 通知girl收到消息
this.noticeGirl = opt.name + ',已收到消息';
}
}
}
注意的点:
这里methods中定义的方法introduceSelf就是父组件接收到子组件发出的$emit的事件处理程序
子组件
template
接收来自大群的消息:{{ noticeGirl }}
script
export default {
name: 'girl-group',props: {
girls: {
type: Array,required: true
},noticeGirl: {
type: String,required: false
}
},methods: {
noticeGroup (name,age) {
this.$emit('introduce',{
name: name,age: age
})
}
}
}
注意的点:
子组件使用$emit发出自定义事件
相比于Vue1.x的变化:
$dispatch 和 $broadcast 已经被弃用
*官方推荐的通信方式
首选使用Vuex
使用事件总线:eventBus,允许组件自由交流
具体可见:-和-broadcast-替换
结果
以上所述是小编给大家介绍的Vue2.x中的父子组件相互通信。编程之家 jb51.cc 收集整理的教程希望能对你有所帮助,如果觉得编程之家不错,可分享给好友!感谢支持。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。