What is the correct way to trigger an event specified as a string parameter in the emit() function?

My current goal is to pass the emit name as a string (for example, 'showComponent') from child to parent. I then want to trigger another emit in the emitAction(callbackName: string) function, and finally execute the showComponent() function.

I'm not seeing any errors or warnings, so where am I going wrong?

Parent component:

<script setup lang="ts">

const showLoginPopup: Ref<boolean> = ref(false);

function showComponent() {
  showLoginPopup.value = true;
}

const emit = defineEmits<{
  (event: string): void;
}>()


function emitAction(callbackName: string) {
  emit(callbackName);
}

</script>

<template>
<ActionVue @emitAction="emitAction" v-for="action in actions"
            :title="action.title"
            :description="action.description"
            :buttonTitle="action?.buttonTitle"
            :actionType="action.actionType" />
</template>

Child component:

<script setup lang="ts">
const props = defineProps<Action>();
const emit = defineEmits<{
  (event: 'emitAction', callbackName: string): void;
}>()

</script>

<template>
    <button @click="emit('emitAction', props.actionType)">
     {{  props.buttonTitle }}
    </button>
</template>

Answer №1

Triggering a second emit will only pass the event up to the grandparent component. It is recommended to directly execute the function based on the emit name instead.

child:

<button @click="emit('showComponent')"

parent:

<ActionVue @showComponent="showComponent()">

If you absolutely need to invoke a function using a string value, you can dynamically call the function stored in the current application instance:

Parent component:

<script setup lang="ts">
    import { getCurrentInstance } from 'vue'
    const app = getCurrentInstance()

    function emitAction(callbackName: string) {
          // if callbackName === 'showComponent', runs function showComponent()
          app.setupState[callbackName](); 
    }

    function showComponent() {
        showLoginPopup.value = true;
    }
}

Answer №2

When using emit in the template, it's important to write it as $emit(…). Take a look at my example on Codepen to see how I implement this when calling emit in child components.

<!-- This works fine -->
<button @click="$emit('foo', 'bar')">Click</button>
<!-- This won't work as "emit" is not recognized as a function for the component-->
<button @click="emit('foo', 'bar')">Click</button>

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

Is it possible to create a click event for a mat-icon within a mat form field (either in the matprefix or matsuffix)?

I am working with a mat-form-field and have incorporated a custom mat-icon within it as a matprefix. However, I am now looking to create a click method for that matprefix icon. Despite my attempts to write a click method, it does not seem to be functioning ...

Angular - Showing validation messages post successful execution of two functions

I have encountered an issue with my form submission process involving two functions. When both functions succeed, I want to display a successful validation message. However, currently the success message is displayed even if the second function fails. How ...

Leverage the power of mathematical functions within Angular to convert numbers into integers

In my Angular 7 Typescript class, I have the following setup: export class Paging { itemCount: number; pageCount: number; pageNumber: number; pageSize: number; constructor(pageNumber: number, pageSize: number, itemCount: number) { thi ...

Enhance Summernote functionality by creating a custom button that can access and utilize

Using summernote in my Angular project, I am looking to create a custom button that can pass a list as a parameter. I want to have something like 'testBtn': this.customButton(context, listHit) in my custom button function, but I am unsure how to ...

What sets apart a JSON Key that is enclosed in double quotes "" from one that has no quotes?

Below is my TypeScript object: { first_name:"test", last_name: "test", birthdate:"2018-01-08T16:00:00.000Z", contactNumber: "12312312312", email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e19 ...

Can you please provide an explanation on the functioning of Dependency Injection in Nestjs?

I have been delving into Nest.js and incorporating it into my project structure. Additionally, I have integrated TypeORM into the mix. The concept of Dependency Injection in Nest.js has me feeling a bit perplexed. Project Structure |-APP_MODULE |-app.co ...

The ESLint tool seems to be struggling to detect the package named "@typescript-eslint/eslint-plugin"

Struggling with getting ESLint to function properly on a new Angular project in VS Code. The error message I keep encountering is about failing to load "@typescript-eslint/eslint-plugin". After spending the past 3 hours troubleshooting, I have searched hig ...

What is the best way to associate a select dropdown with a form in Angular 2 using formBuilder

After conducting some research, I was surprised to find that the process is not as straightforward as I had expected. I have come across various methods using ngModel, such as Bind and fetch dropdown list value in typescript and Angular2, among others. Ho ...

Ways to conceal a component based on a specific condition?

In my Angular 8 application, I need to dynamically hide a component based on a specific condition. The condition I want to check is: "status === EcheqSubmissionStatus.EXPIRED" Initially, I attempted the following approach: EcheqProcessComponent templat ...

Step-by-step guide on programmatically activating a radio button

I am working with a radio button and input field. I need the ability to programmatically toggle the radio button so that when this.iAreaOfCoverageForThresholdPasser.average-height is set to true, the radio button appears highlighted. Snippet of HTML: < ...

What is the process of inserting information into a nuxt-link in nuxt.js?

I am currently facing an issue with passing data into nuxt-link. Whenever I click on the link, nuxt-link returns a 404 error and fails to load the file. However, the other two links that use :href and hardcoding seem to be working fine. <template> ...

Guide on toggling a modal in a nested component with a prop in Vue.js

Here is my current child component setup: <Edit @fetchInfo="fetchInfo" :agencyData="agency" :dialogEdit.sync="dialogEdit" ></Edit> This component essentially features a modal. Initially, the modal is hidden: data(){ r ...

"Optimize Your Workflow with the Virtual Assistant Bot Platform and Command Center

As I work on developing a Virtual Assistant for Microsoft Teams, I've noticed some limitations with using adaptive cards due to the version of Teams I'm working with. For example, the buttons always need to be placed at the end of the card. In se ...

Bring in an Angular Component into a different Component by stating the name of the component as an input parameter

In my project, I am looking to develop an angle component made up of multiple sub-components. The end goal is to construct a versatile tree component with nodes that cater to different data types. Each data type in the tree component will import specific s ...

Having trouble with Vue.js not returning HTML elements from methods properly?

I have been attempting to retrieve html elements from a method, and I thought of using v-html for this purpose (not sure if there is a better approach). However, I seem to have encountered an issue with backtick templates and string interpolation. An error ...

What is the best way to enable external events for Fullcalendar in an Angular environment?

Struggling to integrate external events with Fullcalendar and Angular. Admittedly, I am new to Angular and there are aspects that still elude me. Fullcalendar provides a guide on setting up with Angular, available here. Initially, I managed to set up the ...

Utilizing asynchronous operations dependent on the status of a separate entity

Dealing with asynchronous operations in Vue has been a challenge for me. Coming from a C# background, I find the async-await pattern more intuitive than in JavaScript or TypeScript, especially when working with Vue. I have two components set up without us ...

Tips for sending a parameter from a Vue component attribute to the component's SCSS

Recently, I have successfully created a tooltip component using pseudo-classes ::before and ::after. This component positions itself around an element based on the attributes assigned to it on various pages. For instance, here's an example of a toolti ...

Tips for achieving asynchronous data retrieval using Angular Observable inside another Observable

What is my goal? I have several components with similar checks and data manipulation activities. I aim to centralize these operations in an observable. To do this, I created an observable called "getData" within my service... The unique aspect of "getData ...

Angular 5: Unable to add a destroyed View to a ViewContainer

I encountered a new error in my Angular application that I haven't seen before. The issue is arising from this specific line in the Angular source code. This error occurs when I log out and then log back into my app. While on a certain route, there i ...