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.$emit
orvm.$emit
而不是必須顯式指定所有內容的上下文。我最初提出這個想法時沒有意識到這些實例屬性可能是供內部使用的,而下一個 Composition API 的情況并不完全如此。
添加回答
舉報