Is there a more efficient method for invoking `emit` in Vue's Composition API from an external file?

Is there a more efficient way to access the emit function in a separate logic file?

This is my current approach that is functioning well:

foo.js

export default (emit) => {
    const foo = () => { emit('bar') };
    return { foo };
}

When consuming the component:

import { defineComponent } from '@vue/composition-api';
import foo from './foo';

export default defineComponent({
  setup(props, { emit }) {
    const { foo } = foo(emit);
    return { foo };
  }
});

I'm curious if there might be a more suitable method for achieving this. Is it considered bad practice to use emit within a consumable file?

Answer №1

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.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Modify the name of the document

I have a piece of code that retrieves a file from the clipboard and I need to change its name if it is named image.png. Below is the code snippet where I attempt to achieve this: @HostListener('paste', ['$event']) onPaste(e: ClipboardE ...

Trouble of VueJs array data property with .includes() in search for integer value

I'm struggling to figure out how to check if an integer value is already stored in the data property of array type. The Observer type property always returns false when I ask: this.selected.includes(value) Below is my complete example - I cast the va ...

Incorporate the teachings of removing the nullable object key when its value is anything but 'true'

When working with Angular, I have encountered a scenario where my interface includes a nullable boolean property. However, as a developer and maintainer of the system, I know that this property only serves a purpose when it is set to 'true'. Henc ...

Securing page access with a straightforward password protection using Flask

Looking for a straightforward way to add password protection to a Flask app site. I've explored options like flask_login, but they seem overly complex for my needs. I don't need high security or login sessions - just something like: "enter passw ...

What is the best way to utilize window.find for adjusting CSS styles?

Incorporating both AJAX and PHP technologies, I have placed specific text data within a span element located at the bottom of my webpage. Now, my objective is to search this text for a given string. The page consists of multiple checkboxes, with each check ...

Verify the completeness of data types within an array in typescript

I am currently developing a comprehensive match function that I want to ensure is exhaustive during compile time. Although adding a default case would help with this, I am intrigued by some interesting dependent typing techniques I have come across. It wou ...

Effortlessly update data in real-time using Laravel and vue.js

I am dealing with constantly changing API data in my development work. Utilizing Laravel and Vue.js, I can see a continuous flow of data when monitoring the network using F11. However, this does not seem to have any impact on the DOM. Below are some sampl ...

Display the div if the input field is left blank

Is there a way to display the div element with id="showDiv" only if the input field with id="textfield" is empty? <form action=""> <fieldset> <input type="text" id="textfield" value=""> </fieldset> </form> <div id="sh ...

Trouble embedding iframes in local files?

I have recently created a file which includes the following code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8> <style> iframe { height: 500px; width: 600px; } ...

Using the onKeyUp and onKeyDown functions to detect when the spacebar key is pressed

Is there a way for my function to be triggered by either clicking a button or pressing the spacebar? I have managed to make it work partially, but it's not quite right. This is the function in question: const showText = () => { const x = Toug ...

Obtaining a state hook value within an imported function in React

In order to access a value from the state hook stored in a special function, it is straightforward to do so in a functional component. For example, this can be achieved in App.js like this: import React from 'react'; import { Switch, Route, with ...

Error: React - Module not found. This issue arises when attempting to require the 'express' package from within the installed

Hello, I attempted to install the express package in a React project. However, when I try to import the package inside app.js using: const app = require("express"); I encounter 30 errors all stating: Module not found Error: Can't resolve 'x&ap ...

When importing data from a jQuery AJAX load, the system inadvertently generates duplicate div tags

Currently, I am utilizing a script that fetches data from another page and imports it into the current page by using the .load() ajax function. Here is the important line of code: $('#content').load(toLoad,'',showNewContent()) The issu ...

Magnify novice mistakes: Unhandled promise rejection and Ensure every child has a distinct "key" property

Currently, I am working through Amazon's Getting Started with AWS tutorial found here: https://aws.amazon.com/getting-started/hands-on/build-react-app-amplify-graphql/module-four/ After successfully building and hosting the app on git, I noticed that ...

Jasmine is having trouble scrolling the window using executeScript

I usually use the following command: browser.driver.executeScript('window.scrollTo(0,1600);'); However, this command is no longer working. No errors are showing in the console, making it difficult to troubleshoot. Interestingly, the same scri ...

Tips for preventing duplicate Java Script code within if statements

In my function, there are various statements to check the visibility of fields: isFieldVisible(node: any, field: DocumentField): boolean { if (field.tag === 'ADDR_KOMU') { let field = this.dfs_look(node.children, 'ADDR_A ...

Encountering silence: React JS fetch call left unanswered by Sinatra server

Exploring the realms of Sinatra and React JS, I am venturing into making a GET call from my React website to a Sinatra server in order to display plain text. The Sinatra Server script: require 'sinatra' set :root, 'lib/app' before d ...

In search of inspiration to create a recipient list similar to Gmail using Vue3?

Recently, I've been trying to create a recipient list similar to that in Gmail using Vue3 but I'm stuck and unable to find helpful resources online. recipient list I have an array of email addresses that I can loop through and display in a div. ...

Assigning active classes based on the href attributes of child <a> tags

I've created a navigation structure as follows: <ul class="page-sidebar-menu"> <li class="menu"> <a href=""> <span class="title">Menu Item</span> <span class="arrow"></span> < ...

Acquiring the safe area of the iPhone X through JavaScript

The CSS properties safe-area-inset-left, safe-area-inset-right, safe-area-inset-top, and safe-area-inset-bottom are available, but is there a way to retrieve these values using JavaScript? ...