Vue.js is unable to dispatch an event to the $root element

I'm having trouble sending an event to the root component. I want to emit the event when the user presses enter, and have the root component receive it and execute a function that will add the message to an array.

JavaScript:

Vue.component('input-comp',{
  template : `
       <div>
        <input type="text" v-model ="textData" v-on:keyup.enter ="pushMessages"/>
        <button v-on:click="pushMessages">Send text</button>
       </div>`,
  data : function(){
     return {
         textData : 'test Message'
     }
  },
  methods : {
    pushMessages : function(){
      this.$root.$emit('message', { message: this.textData })
    }
  }
})

var vm =  new Vue({
    el : '#parent',
    data : {
      msgs : []
    },
    methods : {
      pushMessages : function(payload){
          this.msgs.push(payload.message)
      }
    },
  updated(){
    this.$root.$on('message', this.pushMessages)
  }
})

HTML:

<div id="parent">
  <p v-for="msg in msgs">{{msg}}</p>
  <input-comp></input-comp>
</div>

Answer №1

My suggestion is to emit the event without using $root in the following way:

 methods : {
    pushMessages : function(){
        this.$emit('message', { message: this.textData })
    }
  }

Then, in the parent component, handle it like this:

<input-comp @message="pushMessages"></input-comp>

Alternatively, you can try using the mounted hook instead of the updated hook:

  mounted(){
     this.$root.$on('message', this.pushMessages)
    }

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

Encountering an issue with importing createSagaMiddleware from 'redux-saga' while working on my create-react-app project

Within my create-react-app, I have the following import: import createSagaMiddleware from 'redux-saga'; However, there seems to be an issue with importing createSagaMiddleware in my system. The versions I am currently using are: node 12.13.0 n ...

Error encounters when attempting to utilize the eloquent save method with data sourced from the Vue frontend

Here is the code I have in a Vue Component: sendUserData(){ axios.post('/api/saveUser', { data: { id: this.id, name: this.name, ...

Guide to displaying API data in HTML format

This university assignment involves working on a homework project where I need to utilize a public API in HTML. So far, I have successfully called the public API to display a list of radio channels in the left menu (without adding any click functionality). ...

What is the best way to leverage multiple random YouTube v3 API keys simultaneously?

I have the following code snippet and I am looking to randomly select an API key from a list of keys: function search() { // Clear Results $('#results').html(''); $('#buttons').html(''); // Get Form Input ...

Sharing API types from a NestJs backend to a Vue frontend (or any other frontend) application: Best practices

In my development setup, I have a VueJs and Typescript Front End app along with a PHP server that is in the process of being converted to NestJs. Both of these projects reside in the same Monorepo, allowing me to share types for DTOs between them. I am ex ...

Tips on avoiding the accumulation of event handlers when dealing with click events triggered by the document selector in jQuery

I am currently working on a project that involves using AJAX to load various pieces of HTML code. This is done in order to properly position dynamic buttons within each portion of the HTML content. In my case, I need to trigger click events on the document ...

Select a hyperlink to access the corresponding tab

I've been playing around with bootstrap and AngularJS. I placed nav-tabs inside a modal-window and have it open when clicking on a link. However, I want the appropriate tab to open directly upon click. For example, if I click on "travel", I want the t ...

"ReactJS error: Unable to upload file due to a 400

Every time I attempt to upload a file, I encounter this error: "Uncaught (in promise) Error: Request failed with status code 404". I'm puzzled as to why this is happening. Here's the section of my code that seems to be causing the issue. ...

Using $state.go within an Ionic application with ion-nav-view may cause unexpected behavior

I recently started working on an Ionic Tabs project. I have a button called "initiateProcess" that triggers some operations when clicked using ng-click. Within the controller, it performs these operations and then navigates to a specific state (tab.target) ...

Vue 3 Single File Component experiencing a type error when assigning v-model to a textarea

I encountered an error in VSCode when trying to use v-model on a <textarea>. The error message states: (property) TextareaHTMLAttributes.value?: string | number | string[] | undefined Type 'Ref<string>' is not assignable to type &ap ...

How to troubleshoot syntax errors when using the delete function in Three.js within Eclipse

When using the Javascript Library Three.js, it is important to note that the delete keyword can be used as an object property. While this is valid under ECMAScript 5 standards, Eclipse currently only supports ECMA 3. As stated in the Mozilla reference, re ...

I am facing some difficulties with my deployed CRA website on Github Pages, as it appears to be malfunctioning compared to when I was running it on localhost using VS Code

After deploying my CRA website on Github Pages, I noticed that it is not functioning the same as it did when running on localhost using VS Code. The site retrieves data from SWAPI and performs manipulations in various React components. While everything wor ...

Obtain information from an HTTP GET call

I have encountered an issue where I am unable to access the data that is passed with an HTTP GET request from the client to my server. Oddly enough, this setup works perfectly fine for POST requests but not for GET requests. The technologies being used ar ...

Incorporate a JavaScript library into a personalized JavaScript file that is utilized within my Angular2 project

Integrating Machine Learning into my Angular2 project using the "synaptic.js" JavaScript library is my goal. After executing the command npm install synaptic --save I intend to execute a custom javascript file (myJsFile.js): function myFunction() { v ...

JavaScript code can be enhanced with HTML comments to improve readability

I have incorporated Google ad into my website using the following code. <script type="text/javascript"><!-- google_ad_client = "pub-"; /*Top 468x15 */ google_ad_slot = ""; google_ad_width = 468; google_ad_height = 15; //--> </script> < ...

Tips for preserving login session continuity following page refresh in Vuejs

signInMe() { this.$store.dispatch('setLoggedUser', true); this.$store.dispatch('setGenericAccessToken', response.data.access_token); this.errorMessage = ""; }, (error) => { if (error) { th ...

Guide to clicking on a user and displaying their details in a different component or view using Vue.js router

Currently working on a Vuejs project that requires the following tasks: Utilize an API to fetch and display a list of users (only user names) on the home page. Create a custom search filter to find users based on their names. Implement functionalit ...

Guide on creating uniform heights and widths for images with varying dimensions utilizing CSS (and percentage values)

Is there a way to ensure that all images maintain the same height and width using CSS percentages, rather than set pixel values? I'm working on displaying images in circles, where most are uniform in size but a few outliers distort the shape. The wide ...

Load JavaScripts asynchronously with the function getScripts

Asynchronously loading scripts on my login page: $.when( $.getScript("/Scripts/View/scroll-sneak.js"), $.getScript("/Scripts/kendo/kendo.custom.min.js"), $.Deferred(function (defer ...

Updating the selected value in TomSelect based on an ajax response

I am facing an issue setting a value on TomSelect using ajax response. Normally, I would use the following code on a general dropdown: $('#homebasepeg').val(data.hmb_id).change(); However, when I try to apply this on TomSelect, it doesn't s ...