八 分分钟学会 vue3组件传参之 自定义事件

169 阅读1分钟

1. 直接在模版中使用

父组件

<template>
  <div class="about">
    <!-- 使用自定义组件 aaa为自定义的事件名称  bbb是父组件接收数据的自定义事件名称-->
    <CustomComponent @aaa="bbb"></CustomComponent>
    <div>我是来自子组件的参数:{{ data }}</div>
  </div>
</template>

<script setup lang="ts">
// 引入自定义组件
import CustomComponent from '@/components/CustomComponent.vue'

import { ref } from 'vue'

const data = ref('')

// 接收子组件的传递过来的参数
const bbb = (val) => {
  data.value = val
}
</script>

子组件

<template>
  <div>
    我是自定义组件
    <!-- 使用 $emit 给父组件穿参数  aaa为自定义的事件名称 -->
    <button @click="$emit('aaa', '我是来自子组件的参数')">点击我给父组件穿参</button>
  </div>
</template>

<script setup>

</script>

<style lang="scss" scoped></style>

image.png

2. 声明触发的事件

父组件

<template>
  <div class="about">
    <!-- 使用自定义组件 aaa为自定义的事件名称  bbb是父组件接收数据的自定义事件名称-->
    <CustomComponent @aaa="bbb"></CustomComponent>
    <div>我是来自子组件的参数:{{ data }}</div>
  </div>
</template>

<script setup lang="ts">
// 引入自定义组件
import CustomComponent from '@/components/CustomComponent.vue'

import { ref } from 'vue'

const data = ref('')

// 接收子组件的传递过来的参数
const bbb = (val) => {
  data.value = val
}
</script>

子组件

<template>
  <div>
    我是自定义组件
    <button @click="customEvent">点击我给父组件穿参</button>
  </div>
</template>

<script setup>
// 接收自定义事件
const emit = defineEmits(['aaa'])

const customEvent = () => {
  // 使用准则定义事件给父组件传递参数
  emit('aaa', '我是来自子组件的参数')
}
</script>

<style lang="scss" scoped></style>

image.png