Vue3子传父 组件传参 defineEmits

defineEmits 属性:用于创建自定义事件,接收子组件传递过来的数据。

注意:如果自定义事件的名称,和原生事件的名称一样,那么只会触发自定义事件。

defineEmits 仅适用于 setup 语法糖,其它写法请见:《Vue3 子传父 组件传参 emit》

// 子组件:创建自定义事件,传递数据
const emit = defineEmits(['自定义事件']);
emit('自定义事件', 数据1, 数据2);

// 父组件:绑定自定义事件,接收数据
<组件标签 @自定义事件="函数名"></组件标签>

const 函数名 = (参数1, 参数2) => {
  console.log(参数1, 参数2);
}

基础使用

一、子组件:创建自定义事件,传递数据。

<template>
  <h3>我是子组件</h3>
</template>

<script setup>
import { ref } from "vue";
let name = ref("张三");
// 创建 myEvent 自定义事件
const emit = defineEmits(['myEvent']);
// 使用 myEvent 自定义事件,传递数据
emit('myEvent', name.value, 999);
</script>

二、父组件:给组件标签绑定自定义事件,接收数据。

<template>
  <h3>我是父组件</h3>
  <p>{{ title }}</p>
  <hr />
  <!-- 绑定 myEvent 自定义事件 -->
  <Child @myEvent="add"></Child>
</template>

<script setup>
import Child from '../components/Child';
import { ref } from 'vue';
let title = ref();
// 创建事件函数,接收数据
const add = (name, num) => {
  title.value = name;
  console.log('我是父组件', name, num);
}
</script>

注:子组件使用自定义事件后,父组件中的事件函数会自动执行。

最终效果:

原创作者:吴小糖

创作时间:2024.1.10 

  • 13
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
组件传参到父组件可以通过自定义事件和$emit方法实现。具体步骤如下: 1.在子组件中定义一个方法,用于触发自定义事件并传递参数。 ```vue <template> <div class="child"> 子组件 <button @click="handleClick">传递参数到父组件</button> </div> </template> <script setup lang="ts"> import { defineEmits } from 'vue' defineEmits(['sendData']) const handleClick = () => { const data = '这是子组件传递给父组件的数据' // 触发自定义事件,并将数据作为参数传递给父组件 emit('sendData', data) } </script> ``` 2.在父组件中通过ref获取子组件实例,并在mounted钩子函数中监听子组件的自定义事件。 ```vue <template> <div class="parent"> 父组件 <Child ref="child" @sendData="handleReceiveData"></Child> <div>接收到的数据:{{ receivedData }}</div> </div> </template> <script setup lang="ts"> import Child from './Child.vue' import { ref, reactive } from 'vue' const child = ref(null) const state = reactive({ receivedData: '' }) const handleReceiveData = (data: string) => { // 接收子组件传递过来的数据 state.receivedData = data } // 在mounted钩子函数中获取子组件实例 const mounted = () => { child.value = ref.value } </script> ``` 3.在父组件中定义一个方法,用于接收子组件传递过来的数据。 ```vue <script setup lang="ts"> import Child from './Child.vue' import { ref, reactive } from 'vue' const child = ref(null) const state = reactive({ receivedData: '' }) const handleReceiveData = (data: string) => { // 接收子组件传递过来的数据 state.receivedData = data } // 在mounted钩子函数中获取子组件实例 const mounted = () => { child.value = ref.value } </script> ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小吴吴吴呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值