The @emit event in vue.js is not being received by the parent component

Within my application, there is a form located in the ManageCards component. This form includes a child component called ImageUpload, which emits an image file and its local URL to the parent component:

<form  class="mb-3"> 
  <div class="form-group">
    <h4>{{card.description}}</h4>
    <textarea  class="form-control" :placeholder="card.description" v-model="card.description"></textarea>
  </div>
  <div>
    <img  v-if="card.picture" class="img-circle" style="width:150px"  v-bind:src="card.picture"></img>
  </div>
  <div id="preview"”>
    <h4>Preview</h4>
    <ImageUpload  :imgUrl="url" @newPicture="updatePicture"></ImageUpload> 
    <button @click="addCard" type="button" class="btn btn-primary btn-block" style="color:white">Save</button>
  </div>
</form>

The method addCard initiates a POST request to send data to the API:

addCard() {
  const formData = new FormData();
  formData.append('title', this.card.title);
  formData.append('description', this.card.description);
  formData.append('imagefile', this.selectedFile);
  formData.append('game_id', this.currentGame.id);
  // ...
}

The values of SelectedFile and card.picture should be updated by the emitted method updatePicture:

updatePicture(imageData) {
  console.log("Received emit");
  this.selectedFile = imageData.file;
  this.card.picture = imageData.picture;
  // ...
}

The structure of the ImageUpload Component is as follows:

<template>
  <div class="Image-Upload-wrapper Image-upload"> 
    <div>
      <input type="file" v-on:change="onFileChange" ref="fileUpload" id="file_picture_input"></input>
      <label for="file_picture_input" class="upload_picture_button">Choose Image</label>
    </div>
    <div id="croppie"></div>     
    <div class="upload-wrapper">
      <button type="button" class="btn btn-primary btn-sm" v-on:click="setImage"&rt;
        Set image   
      </button>
    </div>   
  </div>
</template>

<script>
// Croppie explanation::https://www.youtube.com/watch?v=kvNozA8M1HM
import Croppie from 'croppie';

export default {
  props: [
    'imgUrl'
  ],
  mounted() {
    this.setUpCroppie()
  },
  data() {
    return {
      croppie: null,
      croppieImage: '',
      selectedFile: '',
      picture: '',
      url: '',
    }
  },
  methods: {
    setUpCroppie() {
      let el = document.getElementById('croppie');
      this.croppie = new Croppie(el, {
        viewport: { width: 200, height:200, type:'circle' },
        boundary: { width: 220, height:220 },
        showZoomer: true,
        enableOrientation: true
      });
      this.croppie.bind({       
        url: this.url
      });
    },
    setImage() {
      this.croppie.result({
        type: 'canvas',
        size: 'viewport'
      })
      .then(blob =>fetch(blob))
      .then(res => res.arrayBuffer)
      .then(buf => new File([buf], this.croppieImage.name, { type:'image/png' }))
      .then(file => { 
        this.croppieImage = file;
        this.picture = URL.createObjectURL(this.croppieImage);
        const imageData = {
          picture: this.picture, 
          file: this.croppieImage
        };
        console.log("Ready to emit...?");
        this.$emit('newPicture', imageData);
        this.url = '';
      })
    },
    onFileChange(e) { 
      if (e.target.files && e.target.files.length > 0) {
        this.selectedFile = e.target.files[0];
        console.log("chosen file is: " + this.selectedFile.name);
        this.url = URL.createObjectURL(this.selectedFile);
        this.croppie.bind({
          url: this.url
        });
      } else {
        // No image selected, set it to a default value (e.g. an empty string)
        this.selectedFile = null;
        this.url = '';
      }
    } 
  },
}
</script>

I am able to see the message Ready to emit...? in the console output from the setImage method in the child component. However, I do not see the message Received emit from the emit method in the parent component. As a result, the necessary fields for the POST command remain unpopulated.

If anyone can identify the mistake I might be making (probably something trivial), please do let me know!

Answer №1

Child Component

A child component must specify the events it emits.

Options API
export default {
  emits: ['first-event', 'second-event'],
}
Composition API
const emit = defineEmits(['first-event', 'second-event'])

These declared events will be passed up to the parent component in Vue.

Options API
this.$emit('first-event')
this.$emit('second-event')
Composition API
// After defining const emit
emit('first-event')
emit('second-event')

Parent Component

<ChildComponent @first-event="(e) => ..." @second-event="(e) => ...">

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

Steps for preventing a button from being enabled until all mandatory fields are completed

Is it possible to have a button disabled until all required fields are filled out, with the button appearing grey in a disabled state and changing color when all fields are completed? I am facing an issue where clicking on the previous button is causing ...

Check the feature that retrieves data from a `json` file

In my util file, I have a function that imports and checks whether a given sectionUUID has a video in the JSON file. import multipleVideos from '../data/videos.json' function hasSectionMultipleVideos (sectionUUID) { return multipleVideos.vide ...

What strategies can I use to organize and fuse together my library?

I am intrigued by the concept of modular JS and have decided to create my own small library to experiment with it. Here is my vision for how I want it to function: It will include 5 methods Users can download a full library that exports a global variab ...

Is it possible to obtain the socket.id of a user immediately upon their connection?

Does anyone know how I can send a personalized message to a user when they connect, without broadcasting it to everyone else? I'd like to use their socket ID with the code io.to(theirSocketID).emit('chat message', 'Welcome');, but ...

What causes a ReferenceError when attempting to retrieve the class name of a React component?

Take a look at my React component located in index.js: import React from 'react' import ReactDOM from 'react-dom' class App extends React.Component { render() { return ( <div className="App"> <h1>Hello, ...

Having trouble setting the image source in HTML with Node.js

I am a beginner with nodeJS and I am having trouble setting the src attribute of an img tag in my client side html. My node server is running on port 3000 and everything works fine when I visit http://localhost:3000. Here is the code from my server.js fil ...

Tips for sending information to a child component from a parent in Vue.js

Is there a way to pass the image url to this vue component? I am moving the code to a separate php file that will contain the <script> tag used by Vue, but it seems like it won't recognize the passed data from a parent component. Vue.component( ...

The replace() function is failing to replace the provided inputs

Supposedly, when a user types in certain profanity and submits it, the word is supposed to be replaced with a censored version. Unfortunately, this feature is not working as expected. The word appears uncensored. Do you think implementing if/else stateme ...

Vue multiselect is failing to retrieve the ID and name properties

While implementing the vue multiselect in my form, I customized the options to enable autocomplete functionality using axios post. However, despite returning only the id and name from the controller to the js file, all the properties of the option are bein ...

Prevent Duplicate Service Instances in Angular

After doing some thorough research online, I've identified the root of my issue: multiple instances of a particular service are being created. I need assistance in pinpointing and rectifying this problem within my code. The secondary service is depen ...

Three.js is currently rendering a blank canvas in pure white

After following the tutorial at , my browser only displays a white window. I attempted separating the files into js and html, but no luck. What I have already tried: experimenting with adding/deleting the nomodule parameter in the script tag utilizing a ...

Obtaining data from JSON arrays

My current challenge involves extracting data from the following link: and storing it in my database. However, I am encountering difficulties with manipulating the array in order to retrieve the last unix datetime. Despite multiple attempts to extract th ...

Incorporate the jquery lazy load plugin alongside ZURB foundation data-interchange for optimal performance

Currently, I am engaged in a project that involves utilizing the ZURB foundation framework alongside its data-interchange feature to display various images based on different screen sizes. To learn more about this method, please visit: You can also explo ...

Checking form data validity before submission in JavaScript and PHP

My goal is to send data to a PHP script using the POST method. I need to ensure that the form input is valid before initiating an AJAX request. $('#submitccform').click(function() { function validate() { var valid = true; var messa ...

What could be the reason for the malfunction of my for loop within my JSON operation?

Hi everyone, I'm new to coding and currently working on a project involving Twitch Viewer on FreeCodeCamp. I've managed to extract information from the JSON file and display it in my HTML code. However, I'm encountering an issue where I am ...

Can TypeScript modules be designed to function in this way?

Seeking to create a versatile function / module / class that can be called in various ways: const myvar = MyModule('a parameter').methodA().methodB().methodC(); //and also this option should work const myvar = MyModule('a parameter') ...

What is the best method for selecting or deselecting all checkboxes except for one using a single checkbox in angularjs

$scope.checkAll = function() { if ($scope.selectedAll) { $scope.selectedAll = true; } else { $scope.selectedAll = false; } angular.forEach($scope.MyProducts, function(item) { item.Selected = $scope.selectedAll; }); /*});*/ } <di ...

Performing an axios request using form data in a React JS application

I am trying to figure out how to use axios in react js to make a cURL request that is currently working. Here is the cURL request: curl -k --request GET "BASE_URL_SERVER/sendText" --form "user_id='uidxxxx'" --form "sign_id=" Every time I try to ...

Providing parameters to a dynamic component within NextJS

I am dynamically importing a map component using Next.js and I need to pass data to it through props. const MapWithNoSSR = dynamic(() => import("../Map"), { ssr: false, loading: () => <p>...</p>, }); Can anyone sugges ...

Perform Addition of Two Input Values Automatically without the need for any manual clicking of buttons

Despite trying all available codes, I have been unable to make it work. Here is the code: <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta na ...