加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Vue2.x中的父子组件相互通信的实现方法

发布时间:2020-12-17 02:58:55 所属栏目:百科 来源:网络整理
导读:业务场景:(这里指的是直接父子级关系的通信) 美女(子组件)将消息发送给大群(父组件) 大群(父组件)收到美女发送的消息后再回个信息给美女(子组件) 父组件 template 群消息girl: {{ somebody }} 说: 我 {{ age }} 了。 注意的点: 这里在父组件使用v-on来监听

业务场景:(这里指的是直接父子级关系的通信)

  • 美女(子组件)将消息发送给大群(父组件)
  • 大群(父组件)收到美女发送的消息后再回个信息给美女(子组件)

父组件

template

群消息girl:

{{ somebody }} 说: 我 {{ age }} 了。

注意的点:

  • 这里在父组件使用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中的父子组件相互通信。编程之家 52php.cn 收集整理的教程希望能对你有所帮助,如果觉得编程之家不错,可分享给好友!感谢支持。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读