Unable to run the method in the parent component from the child component

I am attempting to trigger a method to run on a parent component when a button within one of its child components is clicked. I am utilizing single file components with Webpack. Below is the code for the child component:

<template>
  <button v-on:click="add">Click</button>
</template>

<script>
export default {
  methods: {
    add: () => {
      console.log('foo')
      this.$dispatch('addClick')
    }
  }
}
</script>

Here is the code for the parent component:

<template>
  <div id="app">
    <count :total="total"></count>
    <click></click>
  </div>
</template>

<script>
import count from './components/count.vue'
import click from './components/click.vue'

export default {
  components: {
    count,
    click
  },
  data: () => {
    return {
      total: 0
    }
  },
  methods: {
    addToTotal: () => {
      console.log('bar')
      this.total += 1
    }
  },
  events: {
    addClick: 'addToTotal'
  }
}
</script>

The count component simply displays an h1 element that shows the value of the total variable. After clicking the button, "foo" gets logged in the console, but "bar" does not and the total remains unchanged. Any suggestions on what might be the issue? Thank you for your help!

Answer №1

Your methods are currently using lambda notation, causing them to have the incorrect this binding. Switching to regular functions by using function will resolve this issue.

Vue.component('click', {
  template: '#clicker',
  methods: {
    add: function() {
      console.log('foo')
      this.$dispatch('addClick')
    }
  }

})

new Vue({
  el: '#app',
  data: () => {
    return {
      total: 0
    }
  },
  methods: {
    addToTotal: function () {
      console.log('bar')
      this.total += 1
    }
  },
  events: {
    addClick: 'addToTotal'
  }
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>
<template id="clicker">
  <button v-on:click="add">Click</button>
</template>

<div id="app">
  <count :total="total"></count>
  <click></click>
  {{total}}
</div>

Answer №2

Apply the two-way synchronization binding modifier to the total property of the count component in order to automatically update its value when the parent total value changes. See the code snippet below for an example:

Vue.component('click', {
    template: '<button v-on:click="add">Click</button>',
    methods: {
        add: function () {
            this.$dispatch('addClick');
        }
    }
});

Vue.component('count', {
    template: '<h1 v-text="total"></h1>',
    props: {
        total: {
            type: Number,
            twoWay: true
        }
    }
});

new Vue({
    el: '#app',
    data: {
        total: 1
    },
    methods: {
        addTotal: function () {
            this.total++;
        }
    },
    events: {
        addClick: 'addTotal'
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.25/vue.min.js"></script>

<div id="app">
    <count :total.sync="total"></count>
    <click></click>
</div>

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

When attempting to integrate Angular 1.4's new router with components, an issue arises where a warning is triggered stating, "Failed to instantiate controller HeadlinesController

Attempting to work with Angular for the first time and struggling to load a component using data from an http request. Currently encountering a warning when attempting to execute the code with the HTTP request. Receiving a "Could not instantiate control ...

Tips for identifying emails from protected platforms such as ProtonMail or Hushmail

A question for the community: So, I have a website that's totally above board and legitimate. Lately, I've noticed some shady characters trying to register from email domains like Proton and Hush - yikes! Before I dive into PhoneText validation, ...

Learn how to extract substrings from a variable within an API using Vue.js

Exploring VueJs for the first time and looking to split a string by comma (,) retrieved from an API into separate variables. The data is coming from a JSON server. "featured-property": [ { "id": "1", " ...

Implementing jQuery autocomplete on dynamically generated fields post page load

I have successfully implemented jQuery UI Autocomplete to fetch data from a DB and populate a form dropdown. However, I am faced with the challenge of adding more form fields dynamically that also need to have the autocomplete feature applied to them. Is ...

Leveraging Python to authenticate on a website using JavaScript and secure HTTPS connection

I am looking to utilize python for logging into a website that utilizes javascript and https encryption. The specific site I'm referring to is: My goal is to create a python script that successfully logs in, with the intention of later translating th ...

Is there a way to effortlessly scroll an element when the CSS overflow property is designated as auto?

I need help with creating a testimonial section where two divs automatically scroll inside a fixed-height container. Currently, only one div is scrolling while the other remains static in my code. I have implemented JavaScript for automatic scrolling wit ...

Compiling this HTML template in dev mode with Vue is agonizingly slow

I've been working with a template app setup that was bootstrapped using vue CLI. Within one of my components, I have 20 nested div tags. During development mode, it's taking roughly 10 seconds to compile this component. The more deeply I nest HTM ...

NPM TypeORM is throwing the error message "Duplicate migrations" when changes are made to a migration file

Recently, I made a modification to an existing table by adding a new column using the command npm run migration:generate <filename>. Unfortunately, I realized later on that I had misspelled the column name and needed to correct it (showComission -&g ...

Tips for transferring a Spring MVC controller variable to JavaScript

I am currently working on retrieving a variable for a JavaScript function from an object that is sent to the view by the controller. The object I am dealing with is called Bpmsn. https://i.sstatic.net/FxlAo.png Through the controller, I have injected th ...

Error encountered: index.html:17 - An InvalidStateError was thrown when attempting to execute the 'send' function on the XMLHttpRequest object. The object's state must be OPENED in order to send the Ajax request

When attempting to run index.html on a local host with xampp, an error is encountered: index.html:17 Uncaught InvalidStateError: Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED.sendAjax @ index.html: ...

Bidirectional Data Binding with Computed Setter in Vue.js

Exploring the concept of two-way data binding with a basic example: <template> <input v-model="fullname"/> <input v-model="first"/> <input v-model="last"/> </template> <script> var app = new Vue({ el: '#a ...

Tips for customizing bootstrap's fixed navbar-default to ensure that the list items align downwards:

Is it possible to customize the bootstrap fixed navbar-default so that the li elements align downward instead of at the top? If you have any corrections or custom solutions, I'd love to see them! Feel free to share your code on platforms like CodePen, ...

Encountering a Type Error while attempting to display items from an array

Encountering an issue while attempting to load quiz questions from a db.json server. The error message reads: "TypeError: this.state.questions[this.state.currentQuestion] is undefined". In order to provide more context, here's a link to a sandbox of m ...

Finding queries in MongoDB collections seem to be stalling

I have been attempting to create a search query to locate a user by their username. Here is the code: userRouter.get('/user/:user_username', function(req, res) { console.log("GET request to '/user/" + req.params.user_username + "'"); ...

Group Hover by StyleX

I recently experimented with the innovative StyleX library and encountered a particular challenge. Can a group hover effect be achieved for a component solely using this library? For instance, let's assume we have the following component in Tailwind ...

Utilizing the powerful combination of AngularJS and Node.js functions

I am facing an issue with the key_client variable as it needs to be loaded with an md5 value obtained from a module called nodejs get-mac. Despite my efforts, I have been unable to make it work successfully. The problem seems to be that key_client is alw ...

Unable to retrieve req.body data, despite having body-parser enabled

I've been working on setting up my login functionality, but I'm running into an issue with accessing the req.body object. Initially, the post route wasn't triggering at all (no console.log output in terminal) and the request would eventuall ...

Showing the name of a class

Hello everyone, I have a piece of JavaScript code that generates HTML buttons when the page loads. The button attributes are fetched from a database through an ASP page. Everything is working fine except for displaying the class attribute - it shows as u ...

Enhance mix-blend mode or filtering effects in SCSS using an SVG component in VueJS

I am currently developing a fixed navbar at the top of a webpage with several SVGs inside anchor tags. I want the SVGs to appear black when displayed over lighter colored divs (other Vue components) and white when displayed over darker colored ones. The ba ...

Utilize Google Tag Manager to Safely Gather Specific Data

My current project involves capturing values from a <select> element, sending them to the Data Layer, and then forwarding them to an Analytics account via Google Tag Manager. The source code I'm trying to extract values from includes a dynamic s ...