"Troubleshooting: Why isn't the Vue $emit function working

My $emit event does not appear to be triggering within the parent component. I am attempting to create a modal popup for an HTML form. In my header component, there is a button that triggers the $emit event. However, when trying to listen for this event in my app.js file within the form component, nothing happens.

Below is the code snippet:

client/src/app.js

<template>
    <div id="app">
        <MainHeader :modalVisability="modal" />
        <OppForm :modalVisability="modal" v-on:showModal="modal = $event"/>

        <div>{{ modal }}</div>
    </div>
</template>

<script>
import MainHeader from './components/MainHeader.vue';
import OppForm from './components/oppForm.vue';

export default {
    name: 'App',
    components: {
        MainHeader,
        OppForm
    },
    data() {
        return {
            modal: false
        }
    }
}
</script>

client/components/MainHeader.vue

<template>
    <div id="main_header_wrap">
        <header>
            <button v-on:click="showOppForm">Add Post</button>
        </header>

        <div>{{ modalVisability }}</div>
    </div>
</template>

<script>
    export default {
        props: {
            modalVisability: Boolean
        },
        methods: {
            showOppForm() {
                this.modalVisability = true;
                this.$emit('showModal', this.modalVisability);
            }
        },
    }
</script>

client/src/components/oppForm.vue

<template>
    <div id="opp_form" >
        <form @submit.prevent="SubmitOpp" v-if="modalVisability">
            <input type="text" name="company_name" v-model="company_name">
            <button type="submit">Submit</button>
        </form>

        <div>{{ modalVisability }}</div>
    </div>
</template>

<script>
    import axios from 'axios';

    export default {
        name: 'oppForm',
        props: {
            modalVisability: Boolean,
        },
        data() {
            return {
                company_name: ''
            }
        },
        methods: {
            SubmitOpp() {
                axios.post('http://localhost:5000/', {
                    company_name: this.company_name,
                })
                .then(function (response) {
                    console.log(response);
                })
                .catch(function (error) {
                    console.log(error);
                });
            }
        }
    }
</script>

Answer №1

I made some improvements to your code. Take a look at the example below:

client/src/app.js

<template>
  <div id="app">
    <MainHeader :modalVisability="modal" @showModal="changeModal" />
    <OppForm :modalVisability="modal" />
    <div>App = {{ modal }}</div>
  </div>
</template>

<script>
import MainHeader from './components/MainHeader.vue';
import OppForm from './components/oppForm.vue';

export default {
  name: 'App',
  components: { MainHeader, OppForm },
  data() {
    return {
      modal: false,
    };
  },
  methods: {
    changeModal(newValueModal) {
      this.modal = newValueModal;
    },
  },
};
</script>

client/components/MainHeader.vue

<template>
  <div id="main_header_wrap">
    <header>
      <button v-on:click="showOppForm">Add Post</button>
    </header>
    <div>MainHeader = {{ modalVisability }}</div>
  </div>
</template>

<script>
export default {
  props: {
    modalVisability: Boolean,
  },
  methods: {
    showOppForm() {
      this.$emit('showModal', !this.modalVisability);
    },
  },
};
</script>

client/src/components/oppForm.vue

<template>
  <div id="opp_form">
    <form @submit.prevent="SubmitOpp" v-if="modalVisability">
      <input type="text" name="company_name" v-model="company_name" />
      <button type="submit">Submit</button>
    </form>
    <div>oppForm = {{ modalVisability }}</div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'oppForm',
  props: {
    modalVisability: Boolean,
  },
  data() {
    return {
      company_name: '',
    };
  },
  methods: {
    SubmitOpp() {
      axios
        .post('http://localhost:5000/', {
          company_name: this.company_name,
        })
        .then(function(response) {
          console.log(response);
        })
        .catch(function(error) {
          console.log(error);
        });
    },
  },
};
</script>

1 - App.js: Listen for the event in MainHeader component.

2 - App.js: OppForm does not need to listen for the event since this component does not change the modal value.

3 - MainHeader.vue: Avoid changing the value of props.

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

Deciphering Encrypted JSON Data

In need of help with our app that generates complex JSON objects where properties and values are in hexadecimal format. How can we convert them back to strings? Example Object: { "636f756e747279": { "6e616d65": "43616e616461", "6 ...

Achieve a successful Vite build even in the presence of TypeScript errors

I am currently facing multiple TypeScript issues in my Vite/Vue/Typescript project that are causing build failures that I am unable to quickly resolve. Upon attempting to build, I encounter the following errors: Found 20 errors in 2 files. Errors Files ...

Using a JavaScript class rather than an ID for toggling visibility

As a complete newbie to JavaScript, I've come across similar questions but I'm lost when it comes to coding - help needed! So here's the code I have so far, and I'm hoping someone can assist me. Currently, I have JavaScript set up to s ...

You cannot assign a promise to a React state

Calling a function from MoviesPage.tsx to fetch movie data results in a promise containing an object that is successfully fetched (can confirm by console logging). However, I'm facing an issue when trying to assign the result to a state - receiving a ...

What is the best way to add a timer to the slider on this page?

I stumbled upon a solution on the internet that fixed my syntax errors - check it out: http://codepen.io/birjolaxew/pen/yJYLyz Although I got past one hurdle, I'm now facing another challenge. How can I integrate setInterval so that the radio is chec ...

Sharing methods between two components on the same page in Angular can greatly improve code efficiency

On a single page, I have two components sharing some methods and properties. How can I utilize a service to achieve this? See the sample code snippet below... @Component({ selector: 'app', template: '<h1>AppComponent1</h1>' ...

"Using AngularJS to display a blank option as preselected in an ng-option

Having an issue with displaying a preselected value as the selected option in my select element. Check out the code below: <select ng-model="data.company" ng-options="company as company.name for company in companies"></select> $scope.compani ...

displaying a pair of distinct elements using React techniques

I need help adding a react sticky header to my stepper component. When I try to render both components together, I encounter an error. To troubleshoot, I decided to render them separately. Surprisingly, when rendering separately, I do not get the "store is ...

What is the best way to trigger a mouseup event in Vue when the mouse is released outside of a specific element?

To capture the mousedown event on the element, you can simply add @mousedown. If the cursor is lifted inside the element, using @mouseup will capture the event. However, if the mouse goes up outside of the element (even outside of the browser window), the ...

An error occurs stating "Unable to access property of undefined while trying to upload a

In my Node.js (v0.10.25) and Express (4.13.1) project, I'm utilizing jade instead of HTML for a registration form. Users can register and upload a profile image through this form. Everything works smoothly except when an empty image is uploaded, whic ...

How can we enable a sitemap for web crawlers in a nodejs/express application?

Looking to enable sitemap for web crawlers in nodejs/express? I am trying to figure out where I should place my sitemap folder/files within the application flow and how to allow access for web crawlers. Currently, when visiting domain/sitemap/sitemap.xml, ...

Changing a JavaScript array by including a numerical value

Here is my original dataset... [{ month: 'Jan', cat: 'A', val: 20 },{ month: 'Jan', cat: 'B',' val: 5 },{ month: 'Jan', cat: &ap ...

"Upon subscribing, the object fails to appear on the screen

Why is the subscription object not displaying? Did I make a mistake? this.service.submitGbtForm(formValue) .subscribe((status) => { let a = status; // a = {submitGbtFrom: 'success'} console.log(a, 'SINGLE ...

How can I restrict a plugin to just one component in Nuxt.js?

I'm working on a blog website using nuxt.js and I need to import an editor in only one component without using the nuxt.config.js file. I've tried the following approach, but it doesn't seem to be working. //Inside '~/plugins/vue2-ed ...

Tips for displaying ajax search results in Laravel views

My attempt to send a JSON response via AJAX to my Laravel view is not yielding any successful results. public function viewMasakanAjax(Request $request) { if($request->ajax()) { $alberMasakan = Masakan::where('alber_nama_masakan&ap ...

The following error occurred while running the command "php artisan ui vue get": ErrorException - Unable to open stream: File

Trying to set up VueJS for my Laravel project, but encountered an error when running php artisan ui vue: Can someone please advise on how to resolve this issue? Thank you. ErrorException > copy(D:\Code\Hung's Friend\management&bso ...

What can be done to ensure that the value from a promise is retained and available for use in

Currently, I am executing a database query and then manipulating the data to obtain a single numeric value. This value is essential for use in a subsequent array. The current definition of the array appears as follows (see below). The issue at hand is tha ...

Combine a segment from two arrays into a single array

I have two arrays and I want to merge them into one while extracting only certain elements... I am using axios with vueJS. (9) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}] 0: Nombredejours: 1.5 Task: {id: "52edcb0e-450f-4de7-b70d-b63e0 ...

What is the best way to retrieve a string from a URL?

Is there a way to extract only a specific string from a URL provided by an API? For instance: I'm interested in extracting only: photo_xxx-xxx-xxx.png Any suggestions on how to split the URL starting at photo and ending at png? ...

What are the reasons and situations where it is beneficial to utilize the input type

Could someone provide an explanation on this subject, detailing its purpose and how it should be understood? <input type="hidden" name="msg" value="GATEFORUM|OE180187|NA|0.00|NA|NA|NA|INR|NA|R|gateforum|NA|NA|F|AMIT SINGH|9993523486|gis16|NA|NA|NA|NA ...