"Switching from dispatch to emit in VueJS: A step-by-step

I need a way to communicate from a child component to its parent in VueJS without using Vuex. I find Vuex too complex for my current level of understanding with VueJS. My project involves single file components.

Here is the code snippet for the child component (child.vue):

<script>
export default {
  name: 'ChildComponent',
  methods: {
    // ajax post here ...
    if (response.data.status === 'accepted'){
      this.$emit('send-data', 'accepted')
    }
  }
}

And here is the code snippet for the parent component (parent.vue):

<script>
import ChildComponent from './ChildComponent.vue'
export default {
  name: 'Parent',
  data () {
    return {
      stage: 1
    }
  },
  components: {
    ChildComponent
  },
  created() {
    // How can I replace 'events' with $on in a single file component and listen for events after all components have been created?
    this.$on('send-data', function(dataResponse) {
      if (dataResponse === 'accepted'){
        this.stage = 2
      }
    })
  }
}

I have come across examples in the VueJS documentation that use eventHub like this:

var eventHub = new Vue()
created() {
  eventHub.$on('add-todo', this.addTodo)
  eventHub.$on('delete-todo', this.deleteTodo)
},

However, I want to be able to listen to events at any time, not just during creation. How can I replace the parent's 'events' with a $on function?

Answer №1

If you listen for the event on created, it will work for the entire lifecycle of the component. Another option is to set the event to trigger using v-on or the @ shortcut when using the component.

For example:

Vue.component('my-component', {
  template: '<div><button v-on:click="sendHello">hello</button></div>',
 
methods:{
sendHello: function(){
console.log('hello');
          this.$emit('hello','hello')
}
}
});
new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!'
  },
methods:{
sayHi: function(){
console.log('say hi')
}
}
})
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>VueJs</title>

</head>
<body>
<div id="app">
  <p>{{ message }}</p>
<my-component v-on:hello='sayHi'></my-component>
</div>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
</body>
</html>

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

Unable to perform a GET request to an API with custom headers

I am attempting to send a GET request to an API, but I am encountering an error: Failed to fetch. What could be causing this issue? const getData = () => { fetch("https://test-docs.stores.kg/api/categories", { method: "GET", he ...

Handling an HTML Form without the Submit Button using VeeValidate

I've implemented a form handler using its composable feature in my <script setup>: const { submitForm, resetForm, handleSubmit, meta } = useForm() function save() { // Want to submit the form here submitForm() // Not working showSaveSnac ...

Angular 2: Applying class to td element when clicked

I am working with a table structured like this <table> <tbody> <tr *ngFor="let row of createRange(seats.theatreDimension.rowNum)"> <td [ngClass]="{'reserved': isReserved(row, seat)}" id={{row}}_{{sea ...

What steps can be taken to avoid including empty tasks in React code?

Is there a way to prevent my application from adding empty tasks? Below is the code snippet for adding a new task to an array. How can I implement a condition to block the addition of empty tasks? This application follows Mozilla's guidelines for a R ...

Encountering a 500 error within a Passport JS and React application

I'm currently developing a chat application using React, and I've hit a roadblock while trying to authenticate users. The axios post request is throwing a 500 error that seems to be elusive. Even when the correct credentials are entered for a use ...

Discovering the final index of an object array within row grouping using ag-grid-vue

Here is an example of an object containing an array of objects: { "Id": "123", "Name": "usb", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="95a4a7a6d5f2f8f ...

Discover the sequence that is the smallest in lexicographical order possible

Here is the question at hand Given a sequence of n integers arr, find the smallest possible lexicographic sequence that can be obtained after performing a maximum of k element swaps, where each swap involves two consecutive elements in the sequence. Note: ...

I am planning to divide my web application into two sections by utilizing react router. I intend to incorporate a router within one of the routes mentioned earlier

/src |-- /components | |-- /signin | |-- SignIn.js | |-- /home | |-- Home.js | | |-- /dashboard | |-- Dashboard.js | |-- /assignee |-- /App.js |-- /index.js Dividing the project into two main parts: signi ...

Tips for choosing elements based on a specific attribute (such as fill color) in D3.js using the SelectAll method

I have various sets of circles on a map - 10 red circles, 10 blue circles, and 10 green circles. Is there a way to use d3 selectAll or select to specifically choose only the red circles? Are there any alternative methods for achieving this? The color of ...

The filter method in combination with slice array functions is not functioning properly

My search input is used to filter an array of users displayed in a table. The table has pagination set up so that only 10 users are shown per page. Oddly enough, the search filter only seems to work on the first page. Once I navigate to another page, the ...

Guide on creating a sitemap using Express.js

I've been working with the sitemap.js package from https://www.npmjs.org/package/sitemap While I can add URLs to the sitemap manually, my challenge lies in adding URLs based on data retrieved from MongoDB. Since fetching data from MongoDB is asynchro ...

Sending a form using an AngularJS dropdown menu

I have recently started using angularjs and decided to switch out a traditional html <select> box for an angular modal select box. The select box successfully populates with data from a $http ajax request, but I am facing issues with form submission ...

Avoiding page refresh when clicking on a button component in React

Apologies if this question has already been addressed. I've done my research but I might be missing something. Currently, I'm working on a React app and I want to ensure that my buttons do not reload the page, but only refresh the state. Here&ap ...

Retrieve a file through a POST request with node.js

Hi everyone, I'm trying to create a "export to excel" functionality in Node.js for a page. By using Chrome DevTools, I discovered that the file is downloaded after a post request, so I need to replicate it. https://i.sstatic.net/aL9SO.png var reques ...

Bring in all SCSS styles from a single file and apply them to a React component

I am attempting to incorporate the entire SCSS file into a React component. I attempted to use the styleName props but was unsuccessful import React from 'react' import Calendar from 'calendar' import { calendarStyles } from './ ...

Manipulate the color of the parent text using a button nested within

I am working on a script that adds a button to div elements with the class name "colors". When the button is clicked, the text color of the parent element will change to a specified color. However, I'm facing an issue where it only changes the last el ...

tips for fetching information from sources beyond observable patterns

Is there a way to retrieve the value of this.dealType outside of the this.trasactionService.transactionEvent$ subscription? I need to access the data and value of this.dealType elsewhere, any help would be appreciated. While it has a value inside the this ...

How do prototype, the $.extend method, and the concept of "return this" all connect with each other?

I've been assigned a legacy project, and I find myself puzzled by the purpose of this code. define(['jquery', 'components/BaseComponent', 'bootstrap'], function( $, BaseComponent, bootstrap ) { 'use strict&a ...

Utilize the sortable script for dynamically loaded items via AJAX

For the drag and drop feature on my website, I am using jQuery sortable. I have a button that displays results with items on the screen. These items can be dragged and dropped into various sections. The issue I'm facing is that if I include the sort ...

Anchor tags created using JQuery will remain on the same page without redirecting

Presented below is the code I have utilized to construct the anchor tag along with its content. $('div#right-slide').html("<a href=\"http://www.XXXXXXXXXXXX.info/limited-specials/\" ><h1 id=\"specials\">Click Here ...