You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js函数式组件无this上下文,如何emit事件?

Fixing Event Emission in Vue Functional Components

Nice catch! The issue here is that Vue functional components don't have their own component instance—so there's no this context, which means the $emit method isn't available directly in the template like it is in regular stateful components.

Luckily, there are two straightforward ways to fix this and get your event bubbling working correctly:

1. Auto-forward all listeners with $listeners (Simplest Approach)

In Vue 2 functional components, the $listeners object contains all event listeners passed down from the parent component. You can bind this directly to your child component to automatically forward all events up to the parent:

<template functional>
  <div>
    <some-child v-on="$listeners"></some-child>
  </div>
</template>

This works because v-on="$listeners" attaches every parent listener to the some-child component. When some-child triggers its change event, it will automatically bubble up to the parent without any extra code.

2. Manually emit specific events with context.emit

If you only need to forward a specific event (not all), you can use the context object available in functional component templates. The context.emit method acts exactly like $emit would in a regular component:

<template functional>
  <div>
    <some-child @change="context.emit('change', $event)"></some-child>
  </div>
</template>

Here, $event captures any data passed along with the change event from some-child—include it if you need to send that data up to the parent component.

Why your original code failed

Functional components lack a component instance, so $emit doesn't exist in their template scope. You have to rely on the context object (which provides access to emit, props, and other component utilities) or $listeners to handle event communication.

内容的提问来源于stack exchange,提问作者Harshal Patil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:14:01