Passing arguments with $emit - Vue

Here is a simple method to handle alerts using $emit. But when passing arguments, it seems like the event is not being triggered at all. The goal is to update the value of alert with the result.

Listening for the event on mount:

this.$eventHub.$on('alert', data =>       
  this.alert = data
})

Works as Expected:

The value of this.alert is set even though it was initially undefined.

this.$eventHub.$emit('alert')

Doesn't Work:

The value of this.alert remains unchanged and the event is not recognized.


this.$eventHub.$emit('alert', {'message':'Signal Test', 'color':'error'})

What could be causing this behavior?

Answer №1

If you want to trigger an event from a vue component, you can achieve this using this.$emit. Consider the following example:

<template>
    <myComponent @customEvent="myCallback($event)" />
</template>

Here is the script code:

export default {
  methods: {
    myCallback(data) {
      console.log(data); // This will display the event data
    }
  }
}

In the child component, you need to emit the event like this:

export default {
  methods: {
    onClick() {
      // Use this.$emit(eventname, data);
      this.$emit('customEvent', 'some data');
    }
  }
}

Answer №2

Instead of providing a solution, I realized that the issue stemmed from user error. It turns out that I was triggering the event and listening for it in the same component. However, by simply relocating the listener to a different component while keeping the code the same, the issue was resolved.

Although this could be intentional design, the lack of output in the console made it unclear whether this behavior was expected or if it was a bug.

I would greatly appreciate any insights or explanations on why this phenomenon occurs!

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

Angular Material Flex is not providing the correct size

There seems to be a problem with certain values for setting the flex property in the Angular Material layout library. The issue is clearly demonstrated in this straightforward example. By clicking through, you can observe that some values display correctl ...

Yarn combined with Webpack fails to execute post-compilation tasks

When using yarn and running yarn prod, I encountered the following error: https://i.stack.imgur.com/2emFk.jpg It seems to be stuck at this particular part of the code: mix.then(() => { execSync(`npm run rtlcss ${__dirname}/Assets/css/admin.css ${__dir ...

Efficient initialization process in Vue.js components

Upon initialization of a component, the data callback is executed as follows: data(){ return { name: myNameGetter(), age: myAgeGetter(), // etc... } }, Following that, a notification is sent to a parent component regarding ...

Executing Javascript code that has been retrieved using the XMLHttpRequest method in a

Would it be feasible to modify this code to function recursively if the redirects to the js file that needs to be executed? function loadScript(scriptUrl) { var xhr = new XMLHttpRequest(); xhr.open("GET", scriptUrl); xhr.onready ...

What could be causing my controller to show {{message}} instead of the message that was set up in the configuration

<!DOCTYPE html> <html> <head> <script src="js/angular.js"></script> <script src="js/Script.js"></script> </head> <body ng-app="LoginPage" ng-controller = "LoginPageController"> <form ...

Customizing AngularJS directives by setting CSS classes, including a default option if none are specified

I have designed a custom directive that generates an "upload button". This button is styled with bootstrap button CSS as shown below: <div class="btn btn-primary btn-upload" ng-click="openModal()"> <i class="fa fa-upload"></i> Upload & ...

What could be the reason behind Cesium viewer's failure to show a model after I upload it?

My application features a 3D map of a city with an "Add building" button. Upon clicking this button, a model of a building should be inserted into the map. However, all I see is a selection marker at the intended location without the actual building appea ...

Why does it appear that Angular is undefined in this straightforward Angular demonstration?

I'm completely new to AngularJS and I've encountered an issue. Yesterday, I ran a very simple AngularJS application that I downloaded from a tutorial and it worked perfectly. The application consists of 2 files: 1) index.htm: <!DOCTYPE htm ...

Error message: Vue warning - The prop "disabled" must be a boolean type, but a function was provided instead

I have this code snippet that I am currently using <v-list-item> <v-btn @click="onDownloadFile(document)" :disabled=getFileExtention >Download as pdf</v-btn > < ...

Next.js triggers the onClick event before routing to the href link

Scenario In my current setup with Next.js 13, I am utilizing Apollo Client to manage some client side variables. Objective I aim to trigger the onClick function before navigating to the href location. The Code I'm Using <Link href={`/sess ...

Whenever I try to import a directory that contains modules, Webpack encounters an error

I am currently in the process of developing a small npm library to streamline API interaction. Here is an overview of my folder structure... dist/ index.js src/ index.js endpoints/ endpoint1.js package.json webpack.config.js Inside my src/index ...

Is it illegal to escape quotes when using an image source attribute and onerror event in HTML: `<img src="x" onerror="alert("hello")" />`?

Experimenting with escape characters has been a fascinating experience for me. <img src="x" onerror=alert('hello'); /> <img src="x" onerror="alert(\"hello\")" /> The second code snippet triggers an illegal character error ...

Navigate to a different HTML file following a JavaScript function in Ionic and AngularJS with Cordova

I am currently creating an Android application in Cordova Tools for Visual Studio using Ionic and AngularJS. My goal is to redirect to another HTML page once my function has completed its execution, but I'm having trouble getting it to work correctly ...

Guide on automatically attaching a file to an input file type field from a database

Currently, I am implementing a PHP file attachment feature to upload files. Upon successful upload, the system stores the filename with its respective extension in the database. The issue arises when trying to retrieve and display all entries from the ...

AngularJS: Triggering events in one controller to update data in another controller

I've tried several examples, but I'm not getting the expected results. In my project, I have two controllers - one for a dropdown and one for a table. When a user selects an item from the dropdown, a factory triggers a get request to update the t ...

Using JavaScript to parse JSON data generated by PHP using an echo statement may result in an error, while

I am facing an issue with parsing a JSON string retrieved from PHP when the page loads. It's strange that if I send an AJAX request to the same function, the parsing is successful without any errors. The problem arises when I attempt to do this: JSON ...

Creating session variables in Joomla using checkboxes and AJAX

I'm currently working on implementing session variables in Joomla with AJAX when checkboxes are selected. Below is the code snippet from select_thumb.ajax.php file: $_SESSION['ss'] = $value; $response = $_SESSION['ss']; echo ...

Prevent redundant Webpack chunk creation

I am currently working on integrating a new feature into my Webpack project, and I have encountered a specific issue. Within the project, there are two entry points identified as about and feedback. The about entry point imports feedback, causing both abo ...

Utilizing lazy evaluation, multiple functions are triggered by ng-click in succession

Successfully disabled ngClick on an element when the scope variable (notInProgress) is set to true as shown below: <a data-ng-click="notInProgress || $ctrl.setTab('renewal');</a> Now, I want to include additional functions to be execut ...

Having trouble connecting to the Brewery API, could use some guidance from the experts (Novice)

I'm currently facing some difficulties connecting to a brewery API (). I am developing a webpage where users can input the city they are visiting and receive a list of breweries in that city. As someone unfamiliar with APIs, I am unsure about the nece ...