uniapp vue3 如何调用组件的事件

在uniapp中使用vue3时,如何正确调用组件的事件?我在父组件中引用了子组件,并尝试通过@eventName监听子组件抛出的事件,但没有触发。请问正确的调用方式是什么?是否需要使用defineEmits或其他特殊写法?

2 回复

在Vue3中调用组件事件,使用ref获取组件实例,然后直接调用方法:

<template>
  <child-component ref="childRef" />
  <button @click="handleClick">触发子组件事件</button>
</template>

<script setup>
import { ref } from 'vue'
import ChildComponent from './ChildComponent.vue'

const childRef = ref()

const handleClick = () => {
  childRef.value.childMethod() // 直接调用子组件方法
}
</script>

子组件需暴露方法:

<script setup>
defineExpose({
  childMethod: () => {
    console.log('子组件方法被调用')
  }
})
</script>

在 UniApp + Vue3 中调用组件事件,主要通过以下方式实现:

1. 子组件触发事件

子组件 (Child.vue)

<template>
  <button @click="handleClick">点击触发事件</button>
</template>

<script setup>
import { defineEmits } from 'vue'

// 定义可触发的事件
const emit = defineEmits(['customEvent', 'anotherEvent'])

const handleClick = () => {
  // 触发事件并传递数据
  emit('customEvent', { message: 'Hello from child!', value: 123 })
}
</script>

2. 父组件监听事件

父组件 (Parent.vue)

<template>
  <Child 
    @custom-event="handleCustomEvent"
    @another-event="handleAnotherEvent"
  />
</template>

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

const handleCustomEvent = (data) => {
  console.log('收到子组件事件:', data)
  // data.message => "Hello from child!"
  // data.value => 123
}

const handleAnotherEvent = (data) => {
  console.log('另一个事件:', data)
}
</script>

3. 使用 ref 直接调用方法

子组件

<script setup>
import { defineExpose } from 'vue'

const childMethod = () => {
  console.log('子组件方法被调用')
}

// 暴露方法给父组件
defineExpose({
  childMethod
})
</script>

父组件

<template>
  <Child ref="childRef" />
  <button @click="callChildMethod">调用子组件方法</button>
</template>

<script setup>
import { ref } from 'vue'
import Child from './Child.vue'

const childRef = ref()

const callChildMethod = () => {
  if (childRef.value) {
    childRef.value.childMethod()
  }
}
</script>

注意事项

  1. 事件命名:建议使用 kebab-case(如 custom-event
  2. 数据传递:可以通过 emit 传递任意数据
  3. TypeScript 支持:可以使用类型定义增强类型安全

这种方式在 UniApp 中与标准 Vue3 用法完全一致,适用于所有平台。

回到顶部