Vue3实战笔记(47)— 一探emit奥秘——组件间通信的艺术与实践


前言

Vue封装了自定义组件之后,如果子组件想要向父组件传递数据该怎么办?

Vue.js 中的 emit 方法就是主要用于组件间的通信,特别是父组件与子组件之间的通信机制。它是 Vue 组件内部触发自定义事件并向父级组件传递数据的一种方式。


一、Vue 2 中的emti

在 Vue 组件中,当你想要向父组件传递信息或通知父组件某个状态发生了改变时,可以使用 $emit。通常情况下,子组件无法直接修改父组件的数据,而是通过定义并触发一个自定义事件,由父组件监听并在回调函数中作出响应。

但是要注意,Vue2和Vue3的用法略有不同。
Vue 2 示例:

<!-- 父组件(parent-component.vue) -->
<template>
  <div>
    <child-component @child-event="handleChildEvent" />
  </div>
</template>
 
<script>
import ChildComponent from './child-component.vue';
 
export default {
  components: { ChildComponent },
  methods: {
    handleChildEvent(data) {
      console.log('接收到的数据:', data);
    }
  }
}
</script>
<!-- 子组件(child-component.vue) -->
<template>
  <div>
    <button @click="sendData">发送数据</button>
  </div>
</template>
 
<script>
export default {
  methods: {
    sendData() {
      this.$emit('child-event', '这是发送的数据');
    }
  }
}
</script>

在这个例子中,子组件 child-component.vue 使用 $emit 方法触发了一个名为 child-event 的自定义事件,并传入了一个参数 data。父组件 parent-component.vue 通过监听 child-event 事件并定义一个处理函数 handleChildEvent 来接收数据。当子组件中的按钮被点击时,会触发 child-event 事件,父组件会接收到数据并在控制台中打印出来。

二、Vue 3的emit

Vue 3 示例:


<!-- 父组件(parent-component.vue) -->
<template>
  <div>
    <child-component ref="childRef" />
  </div>
</template>
 
<script>
import ChildComponent from './child-component.vue';
 
export default {
  components: { ChildComponent },
  setup() {
    const childRef = ref(null);
 
    function handleChildEvent(data) {
      console.log('接收到的数据:', data);
    }
 
    onMounted(() => {
      childRef.value.$on('child-event', handleChildEvent);
    });
 
    onUnmounted(() => {
      childRef.value.$off('child-event', handleChildEvent);
    });
 
    return { childRef };
  }
}
</script>

<!-- 子组件(child-component.vue) -->
<template>
  <div>
    <button @click="sendData">发送数据</button>
  </div>
</template>
 
<script>
export default {
  methods: {
    sendData() {
      this.$emit('child-event', '这是发送的数据');
    }
  }
}
</script>

在这个例子中,父组件 parent-component.vue 使用 ref 属性创建了一个引用,并将其分配给子组件。在 setup 函数中,定义了一个处理函数 handleChildEvent 用于处理自定义事件。在 onMounted 钩子中,使用子组件引用的 $on 方法监听 child-event 事件。在 onUnmounted 钩子中,使用子组件引用的 $off 方法取消对 child-event 事件的监听。当子组件中的按钮被点击时,会触发 child-event 事件,父组件会接收到数据并在控制台中打印出来。


总结

做一个积极向上的人,给自己和他人带来阳光。

  • 18
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值