vue3 defineEmits

本文介绍了如何在Vue3中使用`defineEmits`在父子组件间进行数据传递,无需导入,仅在`<scriptsetup>`块中编译。通过自定义事件实现双向通信。
摘要由CSDN通过智能技术生成

简介:用于父子组件通信时,子组件向父组件传递数据,不需要被导入即可使用,会在编译 <script setup>语法块时一同编译。注意的是 defineEmits 只能在 <script setup>的顶层使用

使用
1、定义子组件

// 子组件 child.vue
 
<template>
  <button @click="handelClick">传递给父级</button>
  <button @click="add">加</button>
  <button @click="decrease">减</button>
</template>
 
<script setup lang="ts">

const emits = defineEmits(['clickFn', 'add', 'decrease'])// 定义一个或多个自定义事件

const handelClick = () => {
  emits('clickFn', { name: '张三', age: 18,id: 1 }) // 第一个参数为自定义事件名  第二个参数为要传递的数据
}
const add = () => {
  emits('add', 10) // 第一个参数为自定义事件名  第二个参数为要传递的数据
}
const decrease = () => {
  emits('decrease', 3) // 第一个参数为自定义事件名  第二个参数为要传递的数据
}

 
</script>

2、定义父组件

// 父组件 parent.vue
 
<template>
  <child @clickFn="updateInfo" />
  <button @click="handelClick">传递给父级</button>
  <button @click="handelAdd">加</button>
  <button @click="handelDecrease">减</button>
</template>
 
<script setup lang="ts">
import child from './child.vue'
import { ref } from 'vue'
const num = ref(10)

const updateInfo = (userInfo) => {
  console.log(userInfo) // { name: '张三', age: 18,id: 1 }
}
const handelAdd = (n) => {
  num.value += n
}
const handelDecrease = (n) => {
  num.value -= n
}
 
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值