Introduction: When used for communication between parent and child components, the child component passes data to the parent component. It can be used without being imported. It will be
<script setup>
compiled together when compiling the syntax block. Note that defineEmits can only<script setup>
be used at the top level of
Use
1. Define subcomponents
// 子组件 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. Define the parent component
// 父组件 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>