vue3组件通信--自定义事件

66 阅读1分钟

自定义事件是典型的子传父的方法。 为什么叫自定义事件呢?是因为我们用@sendToy="getToy"这种格式写,很显然,在DOM中,没有叫sendToy的事件。

父组件FatherComponent.vue:

<script setup>
import ChildComponent from "@/components/ChildComponent.vue"
import {ref} from "vue"

const childToy = ref('')
const getToy = (value) =>{
childToy.value = value
}
</script>

<template>
<div class="bg-blue h-75 w-100 ma-auto">
  <h1 class="text-center">我是父组件</h1>
  <h3 class="ma-6">儿子给我的玩具:{{childToy}}</h3>

  <!--给子组件绑定事件-->
  <ChildComponent @sendToy="getToy"></ChildComponent>
</div>
</template>

在上面的代码中,@sendToy="getToy",我们用这种格式,给子组件绑定了叫sendToy的事件。

子组件ChildComponent.vue:

<script setup>
import {ref} from "vue"

const toy = ref('奥特曼')

//接受父亲传过来的事件
const emit = defineEmits(['sendToy'])
</script>

<template>
  <div class="bg-purple h-50 w-75 ma-auto">
    <h1 class="text-center">我是子组件</h1>
    <h3 class="ml-6">儿子的玩具:{{toy}}</h3>
    <v-btn @click="emit('sendToy',toy)" class="bg-blue text-white ml-6">把玩具给父亲</v-btn>
  </div>
</template>

在子组件中,用defineEmits来抛出sendToy事件。 在v-btn标签中,用@click="emit('sendToy',toy)"这种格式调用sendToy事件,并且把子组件的数据toy也带上。 在这里插入图片描述