当前位置:Gxlcms > JavaScript > Vue2.x中的父子组件相互通信的实现方法

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

时间:2021-07-01 10:21:17 帮助过:38人阅读

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

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

父组件

template

  1. <template>
  2. <div>
  3. <p>群消息girl:</p>
  4. <div>
  5. {{ somebody }} 说: 我 {{ age }} 了。
  6. </div>
  7. <hr>
  8. <v-girl-group
  9. :girls="aGirls"
  10. :noticeGirl="noticeGirl"
  11. @introduce="introduceSelf"></v-girl-group>
  12. </div>
  13. </template>

注意的点:

  • 这里在父组件使用v-on来监听子组件上的自定义事件($emit的变化),一旦发生变化noticeGirl方法就会触发
  1. <script>
  2. import vGirlGroup from './GirlGroup'
  3. export default {
  4. name: 'girl',
  5. components: {
  6. vGirlGroup
  7. },
  8. data () {
  9. return {
  10. aGirls:[{
  11. name:'小丽',
  12. age:22
  13. },{
  14. name:'小美',
  15. age:21
  16. },{
  17. name:'小荷',
  18. age:24
  19. }],
  20. somebody:'',
  21. age:'',
  22. noticeGirl:''
  23. }
  24. },
  25. methods: {
  26. introduceSelf (opt) {
  27. this.somebody = opt.name;
  28. this.age = opt.age;
  29. // 通知girl收到消息
  30. this.noticeGirl = opt.name + ',已收到消息';
  31. }
  32. }
  33. }
  34. </script>

注意的点:

这里methods中定义的方法introduceSelf就是父组件接收到子组件发出的$emit的事件处理程序

子组件

template

  1. <template>
  2. <div>
  3. <ul>
  4. <li v-for="(value, index) in girls">
  5. {{ index }} - {{ value.name }} - {{ value.age }}
  6. <button @click="noticeGroup(value.name,value.age)">发送消息</button>
  7. </li>
  8. </ul>
  9. <div>接收来自大群的消息:{{ noticeGirl }}</div>
  10. </div>
  11. </template>

script

  1. <script>
  2. export default {
  3. name: 'girl-group',
  4. props: {
  5. girls: {
  6. type: Array,
  7. required: true
  8. },
  9. noticeGirl: {
  10. type: String,
  11. required: false
  12. }
  13. },
  14. methods: {
  15. noticeGroup (name, age) {
  16. this.$emit('introduce',{
  17. name: name,
  18. age: age
  19. })
  20. }
  21. }
  22. }
  23. </script>

注意的点:

子组件使用$emit发出自定义事件

相比于Vue1.x的变化:

$dispatch 和 $broadcast 已经被弃用

*官方推荐的通信方式

首选使用Vuex

使用事件总线:eventBus,允许组件自由交流

具体可见:https://cn.vuejs.org/v2/guide/migration.html#dispatch-和-broadcast-替换

结果

以上所述是小编给大家介绍的Vue2.x中的父子组件相互通信,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

人气教程排行