javascript - 如何从 Vue.js 功能组件发出事件?

标签 javascript vue.js vuejs2

正如问题的标题,this 上下文在功能组件中不可用。那么,如果我必须发出一个事件,我该怎么做呢?

例如下面的代码片段:

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

我的功能组件没有 this 上下文,因此 $emit 不可用。我怎样才能冒泡这个事件?

最佳答案

子组件

<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>

See it in action on codesandbox

Do you want to emit the event from the vue instance?

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"
    );
  }
};

See it also a sandbox example here

关于javascript - 如何从 Vue.js 功能组件发出事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50288996/

相关文章:

html - 滚动到 div 的底部不起作用

php - laravel 6 护照中未经授权的 401 错误

vue.js - 捆绑后,vuetify 需要 500kb bundle 大小

javascript - 使用 vue 分布式文件中定义的函数

javascript - 提交表单后将引导模式显示为 "thank you"

javascript - 解决 eslint(node/no-unsupported-features/es-syntax) - 如何在 ESLint 中支持 JavaScript 模块?

javascript - 聊天应用程序的自下而上布局设计

internationalization - vue-i18n 中的动态本地化

javascript - 使用javascript调整div和背景的大小

javascript - 从 YT API JSON 获取 YouTube 横幅