如何从 Vue.js 功能组件发出事件? [英] How to emit an event from Vue.js Functional component?
问题描述
作为问题的标题,this
上下文在功能组件中不可用.所以如果我必须发出一个事件,我该怎么做?
例如在下面的代码片段中:
<模板功能><div><some-child @change="$emit('change')"></some-child>
</模板>
我的功能组件没有 this
上下文,因此 $emit
不可用.我怎样才能让这个活动冒泡?
这在文档 将属性和事件传递给子元素/组件:
<块引用>如果您使用基于模板的功能组件,您还必须手动添加属性和侦听器.由于我们可以访问各个上下文内容,我们可以使用 data.attrs
传递任何 HTML 属性和 listeners
(data.on
的别名)code>) 传递任何事件侦听器.
在最基本的层面上,您可以像这样委派所有侦听器:
如果只想绑定change
监听器,可以这样做:
<some-child @change="listeners.change"></some-child>
但是如果 listeners.change
未定义/为空(未提供给功能组件),这将失败.
如果你需要处理没有change
监听器的情况,那么你可以这样做:
否则你将不得不通过手工编写渲染函数来解决,因为我认为不可能有条件地将 change
监听器分配给
在功能组件的模板中.(或者你可以吗?我不确定.)
As the title of the question, this
context is not available in the functional component. So if I have to emit an event, how can I do that?
For example in below code snippet:
<template functional>
<div>
<some-child @change="$emit('change')"></some-child>
</div>
</template>
My functional component doesn't have this
context and hence $emit
is not available. How can I bubble-up this event?
This is explained in the docs Passing Attributes and Events to Child Elements/Components:
If you are using template-based functional components, you will also have to manually add attributes and listeners. Since we have access to the individual context contents, we can use
data.attrs
to pass along any HTML attributes andlisteners
(the alias fordata.on
) to pass along any event listeners.
At the most basic level, you can delegate all listeners like this:
<some-child v-on="listeners"></some-child>
If you only want to bind the change
listener, you can do:
<some-child @change="listeners.change"></some-child>
but this will fail if listeners.change
is undefined/null (not provided to the functional component).
If you need to handle the situation where there is no change
listener, then you can do this:
<some-child @change="listeners.change && listeners.change($event)"></some-child>
otherwise you would have to settle by writing the render function by hand, since I don't think it is possible to conditionally assign the change
listener to <some-child>
in the template of a functional component. (Or maybe you can? I'm not sure.)
这篇关于如何从 Vue.js 功能组件发出事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!