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>
相关推荐
摘星编程24 分钟前
React Native for OpenHarmony 实战:Picker 选择器组件详解
javascript·react native·react.js
摘星编程1 小时前
React Native for OpenHarmony 实战:VirtualizedList 虚拟化列表
javascript·react native·react.js
谢尔登1 小时前
Vue3 响应式系统——computed 和 watch
前端·架构
愚公移码1 小时前
蓝凌EKP产品:主文档权限机制浅析
java·前端·数据库·蓝凌
摘星编程1 小时前
React Native for OpenHarmony 实战:RefreshControl 下拉刷新组件
javascript·react native·react.js
欣然~3 小时前
法律案例 PDF 批量转 TXT 工具代码
linux·前端·python
一个小废渣3 小时前
Flutter Web端网络请求跨域错误解决方法
前端·flutter
鸣弦artha3 小时前
Flutter框架跨平台鸿蒙开发——Extension扩展方法
android·javascript·flutter
符文师4 小时前
css3 新特性
前端·css3
ct9784 小时前
WebGL开发
前端·gis·webgl