If you have already found the solution, that's great! But if you want to try a similar approach as asked in the original question, there is an option called getCurrentInstance
which has an emitter (the Vue 2 plugin for Composition API also has one).
import { getCurrentInstance } from 'vue';
export default () => {
const { emit } = getCurrentInstance();
const foo = () => {
emit('bar');
};
return { foo };
}
Just keep in mind that this method will only work when calling functions/components that have the SetupContext
.
Edit
The above solution is tailored for Vue 3, but with older versions of Vue + the Composition API plugin, there is a slight difference: Just like other Instance Properties, you need to prefix it with $
to use $emit
. (The following example assumes Typescript as the target language, mentioned in the comment).
import { getCurrentInstance } from '@vue/composition-api';
export default () => {
const { $emit, ...context } = getCurrentInstance() as NonNullable<ReturnType<typeof getCurrentInstance>>;
const foo = () => {
$emit.call(context, 'bar');
};
return { foo };
}
For Vue 3's Composition API, they have the ComponentInternalInstance
interface exported.
P.S. It might be better to stick to assigning the instance to a variable and using context.$emit
or vm.$emit
instead of explicitly specifying a context for everything. This idea was initially generated without realizing that those Instance Properties are mainly for internal uses, which may not apply to the next Composition API.