Skip to content

自定义事件冒泡问题 #13243

Closed
Closed
@blcyzycc

Description

@blcyzycc

我尝试写一个可多层嵌套的组件,并模拟dom树的事件冒泡功能,如下:

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

const emit = defineEmits(['onTest'])

const onClick = () => {
let re = emit('onTest')
console.log(re);
}
</script>

当我在父组件通过 @ontest="onTest2" 并在 onTest2 中返回值,
父组件中的代码:
const onTest2 = () => {
return 1
}

发现 let re = emit('onTest') 并不能接收到,这样自定义事件冒泡效果就无法事件。

只能只能将事件方法通过 v-bind 绑定,以属性的形式传入,这样虽然能在 子组件中通过 props.onTest() 触发事件并接收到返回值。
但是如果 子组件是通过 v-for 循环渲染的,那么事件传参又是个问题,所有有没有更好的方式实现这个功能呢?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions