你如何在 Vue 中向父布局槽发出事件?

  • 本文关键字:布局 出事件 Vue vue.js
  • 更新时间 :
  • 英文 :


我正在尝试弄清楚如何选取在<slot/>组件中触发的事件。

这是我的组件

<template>
<button @click"$emit('event')">Submit</button>
</template>

它会发出我想在父布局的插槽中捕获的事件。

<template>
<slot @event="doThis"/>
</template>

我该如何实现这一点。我的一些阅读使我进入了范围槽,但我不是100%确定。

在 Vue3 中,你可以公开 slot 属性 (slotProps(,从而公开像这样的模板方法。

我的组件

<template>
<!-- action will be exposed in slotProps -->
<slot name="mySlotName" :action="myDefaultAction">
<!-- default slot component, <button> for example? -->
<button @click="myDefaultAction($event)" />
</slot>
</template>
<script>
// ... export default data etc. ...
methods: {
myDefaultAction(event) {
// do something
}
// ...
</script>

如何使用这个?

OtherComponent(使用 MyComponent(

<template>
<MyComponent>
<!-- destructuring slotProps -->
<!-- here action() == myDefaultAction() -->
<template #mySlotName="{ action }">
<!-- define another behavior or layout for the slot -->
<button @click="anotherBehavior($event, action)" />
</template>
</MyComponent>
<!-- Other components... -->
</template>
<script>
// ... export default data etc. ...
methods: {
anotherBehavior(event, action) {
// do something else
// ...
// or call the default action if necessary 
action(event);
}
// ...
</script>

关于 Vue3 老虎机的文档

使用事件总线刷新事件,以便任何组件都可以在侦听时捕获它,如下所示:

在事件总线中.js

import Vue from 'vue';
export const EventBus = new Vue();

在父组件和子组件中导入事件总线文件: 从 './event-bus.js' 导入 { EventBus };

在父组件中,侦听以下事件:

methods:
{
const clickHandler = function(params) { /*Do whatever */ }
}
mounted()
{
EventBus.$on('event', clickHandler);
}

在子组件中,可以按如下方式触发事件:

<template>
<button @click="EventBus.$emit('event', params)">Submit</button>
</template>

最新更新