Vue Composition API:是否有更好的方法在消耗性文件中调用“emit”?

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或者在消耗性文件中调用是一种不好的做法吗?


SMILET
浏览 84回答 1
1回答

慕莱坞森

您可能已经找到了解决方案,但如果您尝试类似的方式(正如问题中最初提出的那样),有一个称为getCurrentInstance发射器的选项(用于 Composition API 的 Vue 2 插件也有一个)。import { getCurrentInstance } from 'vue';export default () => {  const { emit } = getCurrentInstance();  const foo = () => {    emit('bar');  };  return { foo };}但请记住,这仅适用于调用具有SetupContext.编辑上述解决方案适用于 Vue 3,但对于早期版本的 Vue + Composition API 插件,有一点细微的差别:与其余的Instance Properties一样,您必须在其前面加上前缀$to be $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导出了这个接口。PS 最好坚持将实例分配给变量的老式方法,然后执行context.$emitorvm.$emit而不是必须显式指定所有内容的上下文。我最初提出这个想法时没有意识到这些实例属性可能是供内部使用的,而下一个 Composition API 的情况并不完全如此。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript