vue3子组件传值给父组件
# 原理
使用defineEmits
,官方文档
App.vue(父组件)
/src/App.vue
<script setup lang="ts">
import HelloWorld from "./components/HelloWorld.vue";
const Hello = () => {
console.log("Hello");
};
const Hello2 = () => {
console.log("Hello2");
};
</script>
<template>
<HelloWorld @change="Hello" @update="Hello2" />
</template>
<style>
</style>
HelloWorld.vue(子组件)
/src/components/HelloWorld.vue
<script setup lang="ts">
const emit = defineEmits<{
(e: "change", id: number): void;
(e: "update", value: string): void;
}>();
const decrement = () => emit('update', '456');
</script>
<template>
<button type="button" @click="$emit('change', 123)">btn1</button>
<button type="button" @click="decrement">btn2</button>
</template>
<style scoped>
</style>
演示了两种调用方式