Javascript 如何从Vue.js功能组件发出事件?
作为问题的标题,Javascript 如何从Vue.js功能组件发出事件?,javascript,vue.js,vuejs2,Javascript,Vue.js,Vuejs2,作为问题的标题,此上下文在功能组件中不可用。所以,如果我必须发出一个事件,我该怎么做呢 例如,在下面的代码段中: <template functional> <div> <some-child @change="$emit('change')"></some-child> </div> </template> 我的功能组件没有此上下文,因此$emit不可用。我怎样才能使这个事件泡泡起来?
此
上下文在功能组件中不可用。所以,如果我必须发出一个事件,我该怎么做呢
例如,在下面的代码段中:
<template functional>
<div>
<some-child @change="$emit('change')"></some-child>
</div>
</template>
我的功能组件没有
此
上下文,因此$emit
不可用。我怎样才能使这个事件泡泡起来?文档中对此进行了解释:
如果您使用的是基于模板的功能组件,那么还必须手动添加属性和侦听器。由于我们可以访问各个上下文内容,因此可以使用data.attrs
传递任何HTML属性,并使用侦听器
(data.on的别名)传递任何事件侦听器
在最基本的级别上,您可以这样委派所有侦听器:
<some-child v-on="listeners"></some-child>
但是如果侦听器未定义/null(未提供给功能组件),则此操作将失败
如果您需要处理没有更改
侦听器的情况,则可以执行以下操作:
<some-child @change="listeners.change && listeners.change($event)"></some-child>
否则,您必须手工编写渲染函数,因为我认为不可能有条件地将change
侦听器指定给功能组件模板中的
。(或者你可以?我不确定。)如果你想有条件地传递事件侦听器,你可以在功能组件模板中这样做:
对有条件地附加侦听器的问题进行了讨论子组件
<template functional>
<button @click="listeners['custom-event']('message from child')">
Button from child
</button>
</template>
<template>
<div>
<child-component @custom-event="call_a_method" />
</div>
</template>
带有jsx的组件:
导出默认值{
名称:“MyText”,
functional:true,//功能组件
道具:{
价值:{
类型:[字符串,数字],
默认值:“
}
},
渲染(h,上下文){
const{props}=上下文;
//使用jsx
//返回(
// {
//log(context.listeners);
//context.listeners.input(Math.random().toString(36));
//context.listeners[“我的改变](Math.random().toString(36));
//context.data.on.change(Math.random().toString(36));
// }}
// >
//{props.value}
//
// );
//或者使用h函数
返回h(
“h1”,
{
关于:{
//单击h1时发出一些事件
点击:()=>{
//has value prop具有自动输入事件
//事件名称来自父组件中您侦听的事件
log(context.listeners);
context.listeners.input(Math.random().toString(36));
context.listeners[“我的改变](Math.random().toString(36));
context.data.on.change(Math.random().toString(36));
}
}
},
道具价值
);
}
};
conext.listeners
只是context.data.on
的别名。
在父组件中,您应该侦听我的更改
和更改
,否则会出错
组件内的事件名称来自父组件中您侦听的事件
vue 2.6.11运行良好
显示您的代码,没有它我们无法帮助您。@CaShiS,添加了代码片段。建议依赖家长的上下文。监听器typescript呢<代码>侦听器
var具有以下签名:[键:字符串]:函数|函数[]代码>,因此您将得到一个错误:“此表达式不可调用。“Function | Function[]”类型的任何组件都不可调用。ts(2349)“@change=“listeners.change | |(()=>{})”-我从未能够使此模式工作。有人成功测试过它吗?@floodlitworld这是vue模板解析器中的一个缺陷,它无法理解此表达式的类型是函数,也无法正确调用它。相反,您可以执行@change=“listeners.change&&listeners.change($event)”
Nina是正确的,我已经更新了答案。
<template functional>
<button @click="listeners['custom-event']('message from child')">
Button from child
</button>
</template>
<template>
<div>
<child-component @custom-event="call_a_method" />
</div>
</template>
export default {
functional: true,
render(createElement, { listeners }) {
return createElement(
"button",
{
on: {
click: event => {
const emit_event = listeners.event_from_child;
emit_event("Hello World!Is this the message we excpected? :/");
}
}
},
"Pass event to parent"
);
}
};