1 回答

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊
您可能已經(jīng)找到了解決方案,但如果您嘗試類似的方式(正如問題中最初提出的那樣),有一個(gè)稱為getCurrentInstance
發(fā)射器的選項(xiàng)(用于 Composition API 的 Vue 2 插件也有一個(gè))。
import { getCurrentInstance } from 'vue';
export default () => {
? const { emit } = getCurrentInstance();
? const foo = () => {
? ? emit('bar');
? };
? return { foo };
}
但請記住,這僅適用于調(diào)用具有SetupContext
.
編輯
上述解決方案適用于 Vue 3,但對于早期版本的 Vue +?Composition API 插件,有一點(diǎn)細(xì)微的差別:與其余的Instance Properties一樣,您必須在其前面加上前綴$
to be?$emit
。(下面的示例現(xiàn)在假定 Typescript 作為目標(biāo)語言,如評論中所述)。
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,他們確實(shí)ComponentInternalInstance
導(dǎo)出了這個(gè)接口。
PS 最好堅(jiān)持將實(shí)例分配給變量的老式方法,然后執(zhí)行context.$emit
orvm.$emit
而不是必須顯式指定所有內(nèi)容的上下文。我最初提出這個(gè)想法時(shí)沒有意識到這些實(shí)例屬性可能是供內(nèi)部使用的,而下一個(gè) Composition API 的情況并不完全如此。
添加回答
舉報(bào)