``In Vue 2, the component is failing to trigger the main instance function

Currently, I am facing some challenges while working on this web application. It seems like my progress is slower than anticipated and there are certain aspects of Vue 2 that I'm still struggling to grasp.

One issue that I've encountered involves a component that I've integrated into the main Vue instance. While the function within the component, which I $emit, works properly, I'm unable to get the main function to execute as expected.

The component file, PropertyHouseComponent.vue, looks like this:

<template>
    <fieldset class="form-group col-md">
        <div class="form-check">
            <input
                class="form-check-input"
                type="checkbox"
                id="house"
                name="house"
                v-model="data"
                @click="callFunc">
            <label
                for="house"
                class="form-check-label"
            >House</label>
        </div>
    </fieldset>
</template>

<script>
    module.exports = {
        props: {
            value: {
                type: Boolean,
                required: false
            }
        },
        data: function() {
            return {
                data: false
            }
        },
        created: function() {
            if(this.value) {
                this.data = this.value;
            }
        },
        methods: {
            callFunc: function() { <-- The issue lies with calling this method correctly 
                this.$emit('toggleHouse', this.data);
            }
        }
    }
</script>

I've attempted using

this.$parent.$emit('toggleHouse')
instead of @click="callFunc", but it yielded the same result. Additionally, I tried implementing the following code:

watch: {
    data: function(value) {
        this.$emit('toggleHouse', value);
    }
}

The primary Vue instance's function, toggleHouse() in app.js, is outlined below:

Vue.component('property-house', require('./components/PropertyHouseComponent.vue'));
...
toggleHouse: function() { <-- Regrettably, this method is not being invoked
    if(value) {
        this.csHouse = value;
    }
}

In an attempt to troubleshoot, I confirmed that I am passing the 'value' parameter when calling the function by utilizing console.log(). However, this doesn't seem to be the root cause of the problem at the moment.

Lastly, here is the HTML snippet where the component is used:

<property-house :value="true"></property-house>

The rendering in the DOM appears correct based on the provided image: https://i.sstatic.net/LTEDK.png

Hence, I am seeking guidance on what I might be overlooking or doing incorrectly in order to effectively trigger toggleHouse from within the component. Any insights would be greatly appreciated.

Answer №1

Functions are not emitted, events are.

To capture the event, you should be listening for toggleHouse, and it is advisable to avoid camel case in event names (for reasons that go beyond this response).

Let's consider switching to using toggle-house instead.

this.$emit('toggle-house', value)

When implementing the property-house, the code should resemble this

<property-house :value="true" @toggle-house="toggleHouse"></property-house>

Take note of the @toggle-house. This is a shorthand way of listening to events in Vue; alternatively, you could use the full syntax, v-on:toggle-house="toggleHouse".

In both cases (@toggle-house or v-on:toggle-house), a listener is established to monitor the occurrence of the toggle-house event that is being emitted from the child component triggering the toggleHouse method when the event occurs.

Here's a simple example to illustrate.

console.clear()

Vue.component("property-house", {
  template: `
    <div>
      <button @click="$emit('toggle-house', 'Clicked the button')">Click Me</button>
    </div>`
})

new Vue({
  el: "#app",
  methods: {
    toggleHouse(message){
      alert(message)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>

<div id="app">
  <property-house @toggle-house="toggleHouse"></property-house>
 </div>

Answer №2

In order to fix the issue where @click="callFunc" was registering the incorrect checkbox value, I needed to adjust my strategy as it seemed that the event was triggered before updating the v-model="data".

As a result, the updated components now appear like this:

<template>
    <fieldset class="form-group col-md">
        <div class="form-check">
            <input
                class="form-check-input"
                type="checkbox"
                id="house"
                name="house"
                v-model="data">
            <label
                for="house"
                class="form-check-label"
            >House</label>
        </div>
    </fieldset>
</template>

<script>
    module.exports = {
        props: {
            value: {
                type: Boolean,
                required: false
            }
        },
        data: function() {
            return {
                data: false
            }
        },
        created: function() {
            if(this.value) {
                this.data = this.value;
            }
        },
        watch: {
            data: function(value) {
                this.$emit('callback', value);
            }
        }
    }
</script>

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

Using Vue 2 package within Vue 3 project results in an error due to missing functionality of the `$set` method within the package

I've encountered an issue with a package that uses Vue 2 within my Vue 3 project (the problem occurred in versions 3.0.0 and 3.2.37 after updating). Package: https://github.com/Seungwoo321/vue-pivottable Dependencies: "vue": "^2.6.10&qu ...

I am puzzled as to why my personalized Google Maps icons appear in desktop browsers, but are not visible in Android browsers

I have a website that includes a Google Map. The site is built on Wordpress, and each post has specific geographical location meta values generated by the Advanced Custom Fields Maps field. I've designed five custom icons for the map, all hosted on t ...

Function within a while loop

I am attempting to retrieve the content of a specific textarea tag when a particular button is clicked. I believe that using a loop would be helpful in this situation. In PHP, the while loop can be used to dynamically change the name of the textarea and ...

Refresh Jira Gadget AJAX while Viewing Configuration Screen

Having trouble finding a solution to this specific issue and I'm really hoping for a resolution. I am currently working on developing a Jira gadget where I have a configuration screen with two fields. The first one is a quickfind project picker that ...

Display resize grip when hovering

Is there a way to make elements resizable using resize: both, but only show the corner handle when hovering over the element? https://i.sstatic.net/cGIYf.png I am looking for a solution to display that specific handle only on hover. ...

Spreadsheet Layout for my asp.net program

Is there a more efficient tool available for integrating Excel Grid into my asp.net application? I am looking for a tool that will allow me to edit columns similar to Excel and paste data directly into the grid. It should have the same features as Excel. ...

Data binding in one direction with 2 input fields

In the registration form, there are fields for firstname, lastname, and displayname. When the firstname is updated, I want that change to be reflected in the displayname field if it's currently empty. I've set the update to happen on blur, and a ...

Encountering the error message "Unable to retrieve resource: server returned a 404 status code (Not Found)" when trying to display an image

I am new to using React and I'm currently working on a Book project. However, I am facing an issue where the images of the books are not loading in the React app. Here is the directory tree: https://i.sstatic.net/T6ska.png Below is my app.jsx file: i ...

having difficulty assigning a value to the `this.state` variable in a basic input example using Node

export default class extends Component { constructor(props) { super(props) this.state = { searchTerm: ''} this.handleChange = this.handleChange.bind(this) this.handleSubmit = this.handleSubmit.bind(this) } handleCh ...

Why doesn't my constructor promise to not replace data?

I need help figuring out where I'm going wrong with my code. I have a class that has a constructor and two methods. My goal is for the `find()` method to push data from a query into an array. However, I'm not sure why the array values seem to dis ...

You can install the precise version of a package as mentioned in package.json using npm

At this moment, executing the command npm install will download the latest versions of packages. Is there a way to install the exact versions specified in the package.json file? ...

The text decoration feature in CSS is not functioning correctly

I have been working on implementing text differencing in JavaScript using a specific code, and so far, it has been working well. Recently, I attempted to enhance the display by adding a text-decoration that would show a line over incorrect parts of the se ...

Establish a callback function for opening a fresh window using JavaScript

Is there a simple method to assign a "callback" function to a new window opened in javascript? My goal is to execute a function from the parent window in the new window, but I want the parent to be able to specify the name of this specific function (withou ...

What is the reason behind this code performing effectively as middleware but not as a standalone function?

This piece of code functions properly when executed in the following way: app.route('/upload').post(rulesUpload.upload(obj),function (request, response, next) { response.status(200).end('File Successfully Uploaded'); }); However, ...

Click to slide the div down and up when needed

Currently, I am utilizing the code below to implement a slide up/down effect on a div using JavaScript. The slide down action is triggered by a button, while the slide up action is associated with a close text. My goal is to have the button toggle betwee ...

Reactivity issue with Vue's background-image style binding

I am looking to update certain sections of the website based on the selected language without any page refresh. Everything was working fine, but I struggled to dynamically bind a background image when changing the site language (i18n) without refreshing th ...

How to Generate Custom Expiry Tokens with Firebase Authentication

Currently utilizing Firebase 3.4.1 for my web application. The default token expiry length is sufficient to keep users logged in, but I am interested in managing the expiry manually. Ideally, I would like the token to expire at the end of each session by ...

Prevent clicking after triggering the 'click' event on the body element

Hi, I am looking to prevent further clicks on an element after it has been clicked once by the user. The elements are dynamically generated using JavaScript and therefore I cannot apply the usual click prevention code directly. $('.disableClick ...

Trying to filter out repetitive options in an autocomplete box

Using the jQuery autocomplete plugin, I am trying to display 5 unique search results. Initially, I achieved this by limiting the stored procedure to return only 5 results, but now I want to remove duplicates while still showing 5 distinct results. I'm ...

"Enhancing user experience with React.js and Socket.io: dynamically updating list item positions based on

export default class ReactApp extends React.Component { constructor(props) { super(props) this.state = { status: [], services: [] } fetchData((err,opt, data) => { function Exists(l ...