The parent component is ignoring the emitted event from the child

I recently built a form component called Form.vue that is nested within PostPage.vue. In the 'Form.vue' component, I am trying to trigger a $emit event to notify the parent component and update a Prop value called btn-text.

Parent Component PostPage.vue:

<template>
  <div id="post-page">
    <div class="header-text pt-5 text-center">
      <div class="h2 font-weight-bold">
        Welcome to the DevTribe Community
      </div>
      <div class="h5 font-weight-bold">
        Ask questions, share content, introduce yourself. Be nice!
      </div>
    </div>
    <Form />
    <!-- textarea-not-clear isn't catched here below -->
    <Posts
      :btn-text="btnText"
      @textarea-not-clear="changeBtnText()"
    />
  </div>
</template>

<script>
import Form from './PostPage/Form.vue';
import Posts from './PostPage/Posts.vue';
export default {
  name: 'PostPage',
  components: {
    Form,
    Posts
  },
  data() {
    return {

    }
  },
  methods: {
    changeBtnText() {
      console.log('tss');
    }
  }
}
</script>

<style lang="scss" scoped>
#post-page {
    background-color: #ffffff;
    height: 100%;
    padding: 0 20%;

}
</style>


The emit will be triggered within a watch function when the textarea is empty

Child Component Form.vue:

<template>
  <div id="form">
    <form class="text-area text-center mt-5 mx-auto w-100">
      <div class="row">
        <div class="col-12">
          <textarea
            v-model="textarea"
            name="post-text"
            rows="6"
            class="w-100"
            placeholder="Create a post..."
          />
        </div>
        <div class="col text-left">
          <button
            type="button"
            class="btn btn-outline-primary"
          >
            Send
          </button>
        </div>
      </div>
    </form>
  </div>
</template>

<script>
export default {
  name: 'Form',
  data() {
    return {
      textarea: ''

    }
  },
  watch: {
    textarea: function() {
      if (this.textarea !== '') {
        this.$emit('textarea-not-clear', 'Join Discussion');
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.text-area {
    height: 300px;
    textarea {
        border: solid black 1px;
    }
    button {
        width: 120px;
    }
}
</style>


Although the Vue DevTool extension shows the event being triggered: https://i.sstatic.net/MTZhC.jpg

it seems that the event is not being caught properly, as the changeBtnText() function in PostPage.vue is not firing and no console.log('test') message appears.

Answer №1

Before we dive in, let's address the naming issue. Using `Form` as the name for a component can lead to conflicts with standard HTML elements. It's surprising that you're not receiving a warning about this. For more information, check out https://v2.vuejs.org/v2/style-guide/#Multi-word-component-names-essential

Moving on, the issue with your event lies in listening to the wrong component.

<Form />
<!-- The event textarea-not-clear isn't being captured here -->
<Posts
  :btn-text="btnText"
  @textarea-not-clear="changeBtnText()"
/>

The event is triggered by the Form component, but your listener is on the Posts component.

Additionally, I would strongly recommend avoiding the use of ids for components and opting for classes for styling purposes instead.

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

What are some ways to keep text within the boundaries of a div element?

I have tried multiple solutions for this issue, but none seem to be working for me. When I append a paragraph to a div, the text extends beyond the element. Below is the code I am using. Any assistance would be greatly appreciated. CSS: .chat-h { margi ...

Enhance Form within React Calendar

I have developed a calendar using React and Redux. When I click on an empty date, a modal pops up allowing me to add an event. However, I am struggling to implement the functionality to edit that event by clicking on it later. Can someone guide me on the c ...

JQuery Chosen extension - Go back to "Choose an option"

This is a select element with the Chosen plugin applied to it: <label class="radio-inline"><input type="radio" name="reset" value="reset">Reset</label> <select id="listclient"> <option value=""></option> <option val ...

Creating dynamic Vue2 router links based on server-generated data

Currently, I am working on a Vue2 Single Page Application that fetches content from the server and allows clients to edit it in a Content Management System (CMS). The issue I'm facing is that when a user adds a relative link such as /about-us, Vue do ...

Selenium in C#: Timeout issue with SendKeys and Error thrown by JS Executor

Attempting to insert the large amount of data into the "Textarea1" control, I have tried two different methods. The first method successfully inserts the data but occasionally throws a timeout error, while the second method results in a JavaScript error. A ...

When a cursor hovers over an image, a dark line appears

I wanted to create a hover effect where the image would enlarge when hovered over. I achieved this using a JavaScript function that applies the transform property with a scale of 1.2 to the picture. However, during the animation, a black line appears at th ...

Elements in Motion

Working on a parallax effect, I've managed to assign unique scroll speeds to (almost) every element. Moreover, these elements are programmed not to activate their scroll speed until they enter the viewport. Below is the JavaScript code for trigger co ...

Generate a form using code that has the trigger turned off by default

Summary: Looking for a solution to avoid the automatic disabling of a programmatically created trigger in a form. function autoTrigger(e) { var result = {}; var responses = e.response.getItemResponses(); for (var i = 0; i < responses.length; i++) ...

Use the lodash chunk method to split a mapped array into two separate arrays

Looking to organize some data into tables? I have a dataset from an API that you might find helpful. [ { date: "1/11", data: [ { camera: "camera 1", count: 10 }, { camera: "camera 2", count: 20 ...

Experiencing challenges accessing information from the useEffect hook in React

I'm facing some issues with my useEffect hook and I can't seem to figure out why it's not working. I've been trying to make a call to an endpoint, but it seems like I'm not getting any response back. Any help would be greatly appr ...

Guide to linking two variables in Vue.js

I'm working on a project that combines Laravel with Vue. Right now, I'm passing data from the controller to the view in two variables - users and user_data. How can I link these two variables together and display them using v-for? These two tabl ...

What is the best way to reference an ImageButton using jquery?

I created an HTML page with a special div in the body that contains a collection of buttons and images. <div id="div_one"> <button id="button_one"> <asp:Image id="image_button_one" ImageUrl=".." runat="server"> </button> </div& ...

Transfer your focus to the following control by pressing the Enter key

I came across a project built on Angular 1.x that allows users to move focus to the next control by pressing the Enter key. 'use strict'; app.directive('setTabEnter', function () { var includeTags = ['INPUT', 'SELEC ...

Ways to implement a scrollable v-list component using Vuetify

I have set up a v-list using flex layout, where the v-list expands to fill the remaining space horizontally in a column. However, if the list contains many elements with a total height that exceeds the column's height, the list ends up sticking out of ...

Picture goes missing from slideshow

I am currently using a CSS + Javascript slideshow on my website, inspired by an example from the W3Schools website. Here is the code I have adapted for my web application: $(document).ready(function() { var slideIndex = 1; function showSlides(n) { ...

What is the process for aligning rows with the selected option from the drop-down menu

Alright, so here's the scenario: I have created a table along with two drop-down filters. The first filter is for selecting the Year, and it offers options like "All", "2023", "2022", and "2021". When I pick a specific year, let's say "2022", onl ...

What is the best way to trigger a function in Vue when leaving a specific route?

I'm in the process of finding a way to clear local storage when the user navigates away from the current page. How can I achieve this? I attempted to use the destroyed() lifecycle hook but it didn't work as expected. Would utilizing beforeRouteLe ...

Adding numerous pieces of data into the Shopware 6 database through the use of the Administration for handling Many

I recently developed a plugin within the administration of Shopware 6 and I am encountering an issue while trying to insert multiple products associated with vehicles into the database. The specific problem arises when attempting to add '92961afbc50e4 ...

Unable to establish a connection with the docker container

I have developed a server-api application. When running the app on my localhost, only two simple commands are needed to get it up and running: npm install npm start With just these commands, the app runs perfectly on port 3000. Now, I am trying to dock ...

How can elements be connected in Vue using a delimiter?

When it comes to Python, there is a straightforward method to link elements together with a separator solely placed between the "inner" components: >>> print(" → ".join(['hello', 'world', 'bonjour'])) hello → wor ...