Communication between parent and child components in Vue.js to update values and navigate between views

I'm encountering an issue with updating the parent prop in a child view. In my setup, Contestant serves as the parent component, and EditContestant is the child component. Contestant.vue should be responsible for storing user information (potentially using Vuex), while EditContestant.vue's role is to render the edit view, allow for editing user information, and saving it either through its own method or the parent's method. I've set up routing to help illustrate this structure.

The structure looks like this:

Contestant.vue
|-EditContestant.Vue

In Contestant.vue:

<script>
    export default {
        data() {
            return {
                contestant: {
                    id: this.$route.params.id,
                    gender: '',
                    firstname: '',
                    lastname: '',
                },
            }
        },
    methods: {
            fetchContestant(id) {
        //some api call here                            
              vm.updatePropContestant(res.data);
        // ...
            },
            updatePropContestant(newData) {
                if (!this.contestant || this.contestant.length === 0) {
                    this.contestant = {};
                }
                this.contestant.firstname = newData.firstname;
                this.contestant.lastname = newData.lastname;
                this.contestant.id = newData.id;
                this.contestant.gender = newData.gender;
                // this.$forceUpdate();
            },
        },
        }
</script>
<template>
    <div>
        <router-view :contestant="contestant"  @interface="contestant = $event"></router-view>
    </div>
</template>

EditContestant.vue

<script>
    export default {
        data() {
            console.log('data');
            return {
                editContestant: {
                    id: '',
                    'firstname': '',
                    'lastname': '',
                    'gender': 0
                },
                edit: false
            }
        },
        props: ['contestant'],
        created: function () {
// tried also to fetchContestant if parent beforeCreate method with same result, so tried moving it here :(
            this.$parent.fetchContestant(this.$route.params.id);
        }
    }
</script>

<template>
<div class="col">
<input id="firstname" v-model="this.$parent.contestant.firstname" type="text" class="form-control"                                placeholder="First name" 
<!-- this doesn't help either v-on:input="updateParentValue($event.target.value)" --> >
                </div>
</template>

app.js

require('./bootstrap');
window.Vue = require('vue');
import router from './router';
new Vue({
    el: "#app",
    router,
    // render: h => h(app)
});

router/index.js


import contestantComponent from '../components/Contestant/Contestant'
import contestantEditComponent from '../components/Contestant/EditContestant'
Vue.use(Router)
export default new Router({
    routes: [
        {
            path: '/contestant/:id',
            component: contestantComponent,
            children: [
                {

                    name: 'Contestant edit',
                    component: contestantEditComponent,
                    path: '/contestant/:id?/edit',
                },
                {
                    name: 'View contestant',
                    component: ViewContestantComponent,
                    path: '',
                }
            ],
    ]
})

When I add something to the input I get an error:


found in

---> <EditContestant> at resources/js/components/Contestant/EditContestant.vue
       <Contestant> at resources/js/components/Contestant/Contestant.vue
         <Root>
warn @ app.js:41366
logError @ app.js:42625
globalHandleError @ app.js:42620
handleError @ app.js:42580
invokeWithErrorHandling @ app.js:42603
invoker @ app.js:42916
original._wrapper @ app.js:48273

and

app.js:42629 TypeError: Cannot read property '$parent' of null
    at _c.on.input (app.js:37434)
    at invokeWithErrorHandling (app.js:42595)
    at HTMLInputElement.invoker (app.js:42916)
    at HTMLInputElement.original._wrapper (app.js:48273)

Answer №1

Instead of using this. in your template, simply utilize $parent. The template is already within the scope of this..

When communicating between parent and child components, it's recommended to follow the Props down events up pattern instead of directly calling a function through this.$parent.function(). In this case, you should use $emit('callFunc') followed by @callFunc="function".

Answer №2

Make sure to delete this from the this.$parent... line within the EditContestatn.vue 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

Unlocking the contents of an array from a separate file in Next.js

I am developing a Quiz App that consists of two main pages: takeQuiz.js and result.js. My goal is to transfer the data from the multiple-choice questions (mcqs) in takeQuiz.js to be accessible in result.js. Utilizing router.replace(), I ensure that once th ...

Box2dweb: Interaction Point of Collision

Currently working with box2dweb for a game development project. Need assistance in determining the contact point between a "Circle" and "Box". Aware that this can be achieved through b2ContactListener and the Post-Solve Event. Seeking guidance on impleme ...

Angular lazy loading routes do not function as intended

I currently have a project that is divided into different modules. Among these modules, the ones that are lazy loaded include the about and contact modules. The navigation menu containing the router links is located in a feature module alongside the header ...

"Sorry, we couldn't find the page you're looking for" message appears on a website built using Gridsome and hosted on Net

I recently launched a new website using the Gridsome framework deployed with Netlify, but I'm experiencing some issues as the site is not showing up when accessed. Instead, I keep getting an error message from Netlify: Page Not Found Looks like you& ...

What troubleshooting steps should I take to address MQTT issues affecting the rendering of my website while using React and Raspberry Pi?

I am facing an issue where I cannot integrate mqtt with my react application on a Raspberry Pi 4. I am seeking assistance to resolve this problem. My setup includes: Distributor ID: Raspbian Description: Raspbian GNU/Linux 11 (bullseye) Release: 11 ...

Exploring the syntax of typescript when using createContext

Just starting out with typescript and I have some questions. Could someone break down the syntax used in this code snippet for me? What is the significance of having two groups containing signIn, signOut, and user here? Is the first group responsible fo ...

How to retrieve values from HTML class names using Javascript for loops but encountering issues

foreach($products as $row){ <input type="hidden" class="prodId" name="id" value="<?php echo $row['id']; ?>"> <input type="hidden" class="prodUnique" name="unique" value="<?php echo $unique; ?>"> <button id="added" ...

Issue with displaying Images on Datatables using Javascript

I have been scouring the depths of the Internet. Everything was running smoothly, I was handling image uploads and retrievals with NodeJs to MongoDB using the schema below: image: { data: fs.readFileSync(path.join(__dirname, '/public/uploads/&apos ...

The importance of displaying doughnut chart tooltips in Angular 5 console

Is there a way to consistently display tooltips for a doughnut chart? This code snippet might help: Chart.pluginService.register({ beforeRender: function(chart) { if (chart.config.options.showAllTooltips) { // create an array of tooltips // we ...

The curtains fail to load when transitioning to a new page

Currently, I am using curtainjs on my website. The issue I am facing is that when I navigate from my landing page to the about page, curtainjs doesn't work initially. However, upon refreshing the page, everything starts working as expected. Below is ...

Transmit a JSON object to the server using a JavaScript function

I am attempting to transmit a JSON object to a remote server but I am not receiving a success message. Can someone please help me identify what is incorrect in this code: function sendSMS(){ var input = '{"header":"****","****":*****,"****":"**** ...

Arranging serialized information from a tabular format and retrieving specific data

: I'm currently attempting to utilize an AJAX POST request to send data from a dynamic webpage that includes information gathered from a table form, a date selection box, and comment text input. The webpage is generated as a PHP file on a GET request ...

Updating cannot be done while rendering, within the onError function of the Image

I recently encountered a warning stating that I cannot update during render. The recommendation was to update in ComponentWillMount. However, since I need to change the state after checking if the image is in an Error (not Loaded) state, I must make the ...

What is the most effective method for integrating JWT for API requests in Nuxt.js?

I am in the process of developing a frontend using nuxt.js and my primary data is obtained from an API. To handle Authorization, I have implemented JSON Web Tokens (JWT) and now I'm looking for the most effective method to inject the JWT into the Requ ...

The ChartistJs is unable to find the property '_index' of an undefined value, either being 0 or null

I recently incorporated chartistJS to display charts on my website. I have successfully implemented the 'onClick' function provided by chartist. Here is a snippet of the code I used: public horizontalBarchartoptions = { 'onClick&apo ...

Implementing Yii pagination with asynchronous loading

Can anyone help me enable pagination using Ajax in my code? I have a Controller that updates content via Ajax. function actionIndex(){ $dataProvider=new CActiveDataProvider('News', array( 'pagination'=>array( ...

Does a formal gapi library exist specifically for web browsers?

At the moment, I am integrating the "google api" into a web application by linking to the script "". However, I am incorporating it into an "angular4" application that is being bundled with "webpack" and I wish to include and bundle the gapi package as wel ...

The height of the image will be fetched only once from a large collection of images

As mentioned in the title, I have multiple elements with the same class and I am trying to fetch that class to check for the width/height/src of the child image. I am only able to retrieve the height and width of the first image, but I can get the src of ...

`Why is it important to debug javascript code?`

I have some outdated JavaScript code that surprisingly still works in Internet Explorer from 2000-2002, but refuses to function properly in browsers like Firefox, Chrome, and Opera. I've come across various browser quirks where different browsers inte ...

Managing dynamically loaded scripts in Meteor.js

This poses an interesting query: is there a way to regulate which scripts a client is provided with? I've partitioned my code into dynamically loadable segments using the import('dynamically_loadable_file') method, but each time it's ca ...