javascript - Vue 组合 API : Is there a better way in calling `emit` inside consumable file?

标签 javascript typescript vue.js vuejs3 vue-composition-api

访问 emit 的正确方法(或更好的方法)是什么?在分离的逻辑文件中?
这就是我目前所做的工作:
foo.js

export default (emit) => {
    const foo = () => { emit('bar') };
    return { foo };
}
然后在消费组件上:
import { defineComponent } from '@vue/composition-api';
import foo from './foo';

export default defineComponent({
  setup(props, { emit }) {
    const { foo } = foo(emit);
    return { foo };
  }
});
但我想知道是否有更合适的方法来做到这一点?或者调用emit 是一种不好的做法?在消耗品文件中?

最佳答案

您可能已经找到了解决方案,但如果您尝试类似的方式(如最初提出的问题),则有一个名为 getCurrentInstance 的选项具有发射器(Composition API has one too 的 Vue 2 插件)。

import { getCurrentInstance } from 'vue';

export default () => {
  const { emit } = getCurrentInstance();

  const foo = () => {
    emit('bar');
  };

  return { foo };
}
但请记住,这仅适用于调用具有 SetupContext 的函数/组件。 .
编辑
上述解决方案适用于 Vue 3,但适用于较早版本的 Vue + Composition API plugin ,但有细微差别:与 Instance Properties 的其余部分一样,您必须在它前面加上 $成为 $emit . (下面的示例现在假设 Typescript 作为目标语言,如评论中所述)。
import { getCurrentInstance } from '@vue/composition-api';

export default () => {
  // Ugly workaround, since the plugin did not have the `ComponentInstance` type exported. 
  // You could use `any` here, but that would defeat the purpose of having type-safety, won't it?
  // And we're marking it as `NonNullable` as the consuming components 
  // will most likely be (unless desired otherwise).
  const { $emit, ...context } = getCurrentInstance() as NonNullable<ReturnType<typeof getCurrentInstance>>;

  const foo = () => {
    $emit.call(context, 'bar');
  };

  return { foo };
}
然而,对于 Vue 3 的 Composition API,他们确实有这个 ComponentInternalInstance 接口(interface)导出。
附:最好坚持将实例分配给变量的老式方法并执行 context.$emitvm.$emit而不必为所有内容明确指定上下文。我最初提出这个想法时没有意识到这些实例属性可能是供内部使用的,而下一个组合 API 并非完全如此。

关于javascript - Vue 组合 API : Is there a better way in calling `emit` inside consumable file?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64753071/

相关文章:

javascript - 在 Angularjs 中,你如何改变每个测试的模拟服务?

javascript - 对具有单独延迟的元素数组进行迭代

javascript - 如何使用 jQuery 创建多级 jquery Accordion 菜单?

javascript - 无法使用 Angular 从 Assets 文件夹中检索 json 数据

javascript - 在 CSS 中使用 JavaScript 变量(Vue 应用程序)

javascript - 如何从不同组件的一个组件中找到div - vuejs

javascript - 在一个标签中取消订阅可观察到禁用所有?

visual-studio - Visual Studio 2017 的 typescript 支持

javascript - 在 Angular 中迭代 JSON 时出现问题

vue.js - vue-html 不以 html 实体格式打印