Issue with VueJS: Child method not getting executed when passed to parent

Within this context, the parent element is transmitting the name and age props to the child component. The child then emits a customized event called changeAgeFn which transfers its changeAge method back to the parent.

In the parent component, the passed changeAge event is linked to the click action on the button[change age].

Despite this approach not functioning as intended, I am eager to discover the proper or recommended procedure for executing events in a child component from its parent.

Parent.vue

<template>
    <div class="parent-wrap">
        <p>UserName: {{user}}, age: {{age}}
        <button @click="changeAge()"> Change Age</button></p>
        <child :user="user" :age="age" @userChanged="user = $event" @changeAgeFn="$event" ></child>
    </div>
</template>

<script>
    import child from './child.vue'

    export default {
        data: function() {
            return {
                user: 'John',
                age: 35
            }
        },
        components: {
            child
        },        
    }
</script>

<style>
.child-wrap {
  border: 3px solid #000;
  max-width: 300px;
  padding: 20px;
  background: lightblue;
}

.parent-wrap {
  padding: 30px;
  background-color: lightcoral;
  border: 3px solid #000;
}
</style>

child.vue

<template>
    <div class="child-wrap">
        <p>UserName: {{user}}, age: {{age}}
        <button @click="changeName"> Change Name</button></p>
    </div>
</template> 

<script>
    export default {
        props: ['user', 'age'],
        methods: {
            changeName() {
                this.user = 'Rahul'
                this.$emit('userChanged', this.user)
                this.$emit('changeAgeFn', this.changeAge)
            },
            changeAge() {
                this.age = '20'
            }
        }
    }
</script>

Many thanks!

Answer №1

It seems like there may be some confusion here. In order to update the state of the parent component and trigger a re-render of the child component, you need to pass changeAge as a prop from the parent to the child.

The child component should have a prop with the signature:

changeAge: () => void

In the parent component, you define changeAge like this:

// This code belongs in the parent component, not the child component 
methods: {
    ...
    changeAge() {
            this.age = '20'
        }
...

Then, you inject changeAge into the child component like so:

<template>
    ...
    <child :changeAge=“changeAge” etc.../>
    ...
</template>

I hope that clarifies things for you.

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

The catch block is triggered when the dispatch function is called within the try block

It's strange how the code below works perfectly without any errors and records a response once the loginHandler() function is triggered. However, when I include the dispatch function inside the try block after receiving the response, the catch block e ...

Service in AngularJS designed specifically for storing and managing SEO metadata

I stumbled upon a tutorial that introduced me to using a service for dynamic SEO metadata here: However, I encountered an issue - It seems like the service is not accessible outside of the controller's view. <div ui-view></div> Here is t ...

React | The virtual DOM modal refuses to display

I'm currently utilizing React JS in tandem with Ant Design for my latest project. Issue My virtual DOM element features a Popover which contains a Button that, once clicked, displays a Modal. An error is being triggered: Cannot read property ' ...

Tips for incorporating a JavaScript file directly into your HTML code

I'm working with a compact javascript file named alg-wSelect.js, containing just one line of code: jQuery('select.alg-wselect').wSelect(); This script is used by a wordpress plugin. My question is whether it's feasible to incorporate th ...

Error in Redux app: Attempting to access the 'filter' property of an undefined value

I am currently encountering an issue with my reducer: https://i.stack.imgur.com/7xiHJ.jpg Regarding the props actual, this represents the time of airplane departure or arrival, and it is a property within my API. The API structure looks like this: {"body ...

What is the best way to reset react-id-swiper every time an event handler is triggered in a React application?

I have incorporated the react-id-swiper module into my React project to create a dynamic image slider. By setting onClick event handlers on buttons with different id attributes, I trigger API calls that update the state and populate the ImageSlider compone ...

Encountering a TypeError in Mongoose: Unable to access properties of undefined while trying to read 'find'

Encountering an issue with the error message, TypeError: Cannot read properties of undefined (reading 'find'), specifically pointing to this block of code: app.get('/Organizations', (req,res) => { Organizations.find({}).then((organiz ...

How can I determine which component the input is coming from when I have several components of the same type?

After selecting two dates and clicking submit in the daterange picker, a callback function is triggered. I have two separate daterange pickers for SIM dates and Phone dates. How can I differentiate in the callback function when the user submits dates from ...

The creation of a MozillaBrowserBot object has encountered an error

Attempting to access the MozillaBrowserBot object in Mozilla JS has been unsuccessful for me. The code I utilized is shown below: function externalApplication(){ var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Com ...

How to enhance a class in JavaScript by adding a dynamic property

Within my code, I've defined a class which looks like this: class classA { id: number; name: string; constructor(data){ this.id = data?.id || 0; this.name = data?.name || ''; } } What I aim to do now is add ...

Exploring the process of setting up Jasmine tests for both services and controllers in Angular.js

I have been facing challenges in creating accurate tests for my Angular services and controllers, even though they are functioning correctly. I have searched extensively for a solution to this problem. Below is an example of my controller: angular.module ...

JavaScript class with callback function commonly used

I am looking to create a JavaScript class that can register multiple functions to run with a common callback. Each registered function should run asynchronously, and once they have all completed, the specified callback function should be executed. In addi ...

Hide the menu when tapping outside on a tablet device

Currently working with HTML, CSS, and JS (specifically Angular) I have a Header menu that contains dropdown sub-menus and sub-sub-menus in desktop view. On a PC, the sub-menus appear on hover and clicking on an entry redirects you somewhere. Clicking o ...

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 ...

JQuery form plugin - submitting a form automatically on onchange event

As a beginner in JQuery, I am looking to utilize the JQuery form plugin for file uploads and would like to trigger the form submission as soon as a file is selected. This should occur upon the onchange event of the input tag: myfile. <html> <body ...

What causes jquery-ui resizable to set the width of the div with the "alsoResize" property?

I have created a series of divs structured like this: <div id="body_container"> <div id="top_body"> </div> <div id="bottom_body"> </div> </div> Additionally, I have implemented the following funct ...

Encountering an illegal invocation error in jQuery

Recently delving into the world of jQuery, I am attempting to call a C# function from JavaScript using AJAX and jQuery. Additionally, I need to pass some parameters while making the call to the C# function. Here is how I am attempting to achieve this: var ...

Enhance your existing look by incorporating element.style into your designs

Is there a way to add styles onto an html element without overwriting existing css? element.style { "existing css;" } I'm trying to achieve the following result: element.style { existing css; opacity: 0; pointer-events: none; } But current ...

Can you elaborate on the users object found in the npm registry JSON response?

When looking at the json response of any npm package, such as jQuery for example, http://registry.npmjs.org/jquery, you may come across a dictionary called users. This dictionary contains usernames as keys and boolean values as the corresponding values. ...

using javascript to dynamically color rows in a table based on the value in the status field

Hi, I'm new to javascript and seeking help for my table coloring issue. I have a dynamic table where data is inserted through an Ajax call. The goal is to color specific records based on their status. I attempted a solution but only one record gets c ...