vue3 defineEmits

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

使用

1、定义子组件

vue 复制代码
// 子组件 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、定义父组件

vue 复制代码
// 父组件 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>
相关推荐
掘金安东尼20 小时前
TypeScript为何在AI时代登顶:Anders Hejlsberg 的十二年演化论
前端·javascript·面试
yong999020 小时前
MATLAB倍频转换效率分析与最佳匹配角模拟
开发语言·前端·matlab
面向星辰20 小时前
扣子开始节点和结束节点
java·服务器·前端
执携20 小时前
Vue Router (命名视图)
前端·javascript·vue.js
John_Rey20 小时前
Rust类型系统奇技淫巧:幽灵类型(PhantomData)——理解编译器与类型安全
前端·安全·rust
含若飞21 小时前
Vue 中 `watch` 与 `this.$watch` 使用指南
前端·javascript·vue.js
Python私教21 小时前
Node.js 开发环境搭建全攻略(2025版)
javascript
无名小兵1 天前
前端渲染大体积 多页面pdf
前端
c0detrend1 天前
读诗的时候我却使用了自己研发的Chrome元素截图插件
前端·chrome
希冀1231 天前
【Vue】第五篇
前端·javascript·vue.js