为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

SMILET 2023-07-20 14:35:48
emit在分离的逻辑文件中访问的正确方法(或更好的方法)是什么?这就是我目前所做的有效的:foo.jsexport 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或者在消耗性文件中调用是一种不好的做法吗?
查看完整描述

1 回答

?
慕莱坞森

TA贡献1810条经验 获得超4个赞

您可能已经找到了解决方案,但如果您尝试类似的方式(正如问题中最初提出的那样),有一个称为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 的情况并不完全如此。


查看完整回答
反对 回复 2023-07-20
  • 1 回答
  • 0 关注
  • 82 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信