vue3 父组件监听子组件(子组件传递事件给父组件)

7 阅读1分钟

例子:

Child.vue

<template>
  <div>
    <button @click="helloworld">点击获取子组件数据</button>
  </div>
</template>

<script setup>
const emit = defineEmits(['sendhello'])
const helloworld = () => {
  emit('sendhello','nihao','123')
}
</script>

<style scoped>

</style>

App.vue


<template>
  <div>
    <Child @sendhello="hello2"/>
  </div>
</template>

<script setup>
import Child from './components/Child.vue';

const hello2 = (a,b)=>{
  console.log(a,b)
}
  
</script>

<style scoped>

</style>

代码解读: 子组件Child.vue通过defineEmits定义了一个myclick事件,这个事件可以通过emit()函数传递到父组件。