Press the button in the parent component, retrieve information from the child component, and utilize it in a method (Vue 3)

I am currently using Vue3 in combination with Bootstrap 5.

MY ISSUE: I am trying to click a button in my parent.vue. Upon clicking, I want to retrieve the data from my child.vue and access it within the method in my parent.vue.

However, the data always remains empty unless I implement another setTimeout function, which I would like to avoid if possible.

I believe there is a more efficient solution for the props Boolean as well.

If you have any further questions regarding my dilemma, feel free to ask!

Thank you for your assistance!

PARENT:

<template>
  <Child :triggerFunc="triggerFunc" @childData="childData"/>
  <button type="button" class="btn btn-success" @click="get_data()">Get Data</button>
</template>

<script>
  export default {
    data() {
      return {
        triggerFunc: false,
        c_data: [],
      }
    },
    
    methods {
    
      childData(data) {
        this.c_data = data;
      },
    
      get_data() {
        this.triggerFunc = true;
        setTimeout(() => {
          this.triggerFunc = false;
        }, 50);
        
        console.log(this.c_data);
        //HERE I WANT TO USE "C_DATA" BUT IT'S EMPTY. ANOTHER SET_TIMEOUT WOULD WORK, BUT I WANT TO AVOID IT. 


        //IT WORKS LIKE THIS, BUT I PREFER NOT TO USE IT LIKE THAT
        setTimeout(() => {
          console.log(this.c_data);
        }, 50);
      }
    },
  }
</script>

CHILD:

<template>
  <!-- SOME BUTTONS, INPUTS, ETC. IN HERE -->
</template>

<script>
  export default {
    data() {
      return {
        input1: "",
        input2: "",
      }
    },
    
    props: {
      triggerFunc: Boolean, 
    },
    
    triggerFunc(triggerFunc) {
       if(triggerFunc == true) {
         this.save_data()
       }
     }
    
    methods {
      save_data() {
      var data = [
        {
          Input1: this.input1,
          Input2: this.input2
        },
      ]

      this.$emit("childData", data);
    },
    },
  }
</script>

Answer №1

  1. Parent has the ability to hold the data of its children, while the children only display the data. If the children need to update the data, they must send events to the parent. In this scenario, the parent serves as the Key component and the child as a helper for the parent.

    Therefore, the parent always maintains the main copy of the child's data in its own data variables.

  2. It's important to note that using "@" for binding properties is incorrect. "@" is actually used for event binding. For data binding, use ":" as a shorthand for v-bind:

    For example, you can simply write :childData=c_data

PS: It appears that there are some fundamental concepts being misunderstood. Vue is designed to be reactive and automatically binds data to variables, reducing the need for manual intervention. It's recommended to review some basic Vue examples for clarification.

Reference:

Updated code:

PARENT:

    <template>
      <Child @saveClick="saveChildData" :childData="c_data" />
    </template>
    <script>
      export default {
        data() {
          return {
            c_data: [{Input1:"", Input2:""}]
          }
        },
        methods: {
          saveChildData(incomingData) {
            //Either set the new value, or copy all elements.
            this.c_data = incomingData;
          }
        },
      }
    </script>

CHILD:

    <template>
      <!-- SOME BUTTONS, INPUTS, ETC. IN HERE -->
      <!-- Vue will sync data to input1, input2. On button click we can send data to parent. -->
      <button @click.prevent="sendData" />
    </template>

    <script>
      export default {
        props:['childData'],
        data() {
          return {
            input1: "",
            input2: "",
          }
        },
        methods: {
          sendData() {
              var data = [
                {
                  Input1: this.input1,
                  Input2: this.input2
                },
              ]

              this.$emit("saveClick", data); //Event is "saveClick" event.
            },
        },
        beforeMount(){
            //Make a local copy
            this.input1 = this.childData[0].Input1;
            this.input2 = this.childData[0].Input2;
        }
      }
    </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

Problem encountered when attempting to add elements to an array within a nested

When running this code, everything works correctly except for the array pushing. After checking the console.log(notificationdata), I noticed that notification data gets its values updated correctly. However, when I check console.log(notifications), I see ...

What might be causing the in-viewport javascript to not work in my code?

Why is my in-viewport JavaScript code not functioning properly? Link to JSFiddle code When the Click to move button is clicked, the cat image will slide correctly. However, when implementing the following code: if($("#testtest").is(":in-viewport")) ...

Switching from Dom to Jquery

Seeking assistance to convert DOM values into Jquery equivalent. For instance, how can I translate the DOM code: var x = document.querySelector('#x'); into Jquery format? Any suggestions? Additionally, looking for guidance on transforming even ...

Upon concatenation, the screen automatically returns to the beginning of the page

I've set up a page with a list of items, and at the bottom there's a handy "Load more" button that fetches new items to add on top of the existing list: handleLoadProducts = (append = false) => { this.setState({ isLoading: true, ...

I encountered an issue with the "props map error" while working on this

Hello everyone, I am currently in the process of learning React by creating a toggle button for switching between light and dark modes. However, I have encountered an issue when attempting to map through the state and display the data in card format (altho ...

Ways to remove a vuejs component externally

I have constructed a Vue.js component like this: var tree_data = Vue.extend({ template: '#tree_data_template', props: [ 'groupmodal', 'search-name', 'tree-id' ], data: functio ...

Should I use an array literal or split a string?

Imagine you are in need of a predetermined list of words (the focus here is not on the debate surrounding hard-coding). Would you choose this approach: var items = 'apple banana cherry'.split(' '); Or do you favor this alternative: ...

"Utilizing Express's Jade middleware to efficiently handle and manage

Can you create a custom exception handler for errors in jade templates? For example: // server.js app = express(); app.set('view engine', jade); app.locals.js = function () { throw new Error('hello'); } // views/index.jade html != ...

Utilizing a particular iteration of npm shrinkwrap for project dependencies

When deploying my node.js app to Appfog, I encountered a problem with their install script failing to parse npm-shrinkwrap.json. The current format of a dependency in shrinkwrap.json is as follows: "async": { "version": "0.2.10", "from": " ...

Error message: When using Vue CLI in conjunction with Axios, a TypeError occurs stating that XX

I recently started working with Vue.js and wanted to set up a Vue CLI project with Axios for handling HTTP requests. I came across this helpful guide which provided a good starting point, especially since I plan on creating a large project that can be reus ...

The callback function for the XMLHttpRequest object is not triggered when making a cross-domain request using jQuery/Ajax

Looking for some help with this code snippet I have: $.ajax({ xhr: function() { var xhr = new window.XMLHttpRequest(); xhr.addEventListener("progress", function(evt) { if (evt.lengthComputable) { var percentCo ...

Massive React State Array containing hundreds of Input elements, sluggish state updates triggered by onChange events

I am working on a React form that consists of multiple complex inputs, each with its own complex state. To manage the state of all these inputs, I have a parent component where each input is wrapped in a child component. The parent component holds a state ...

What steps should I take to make sure that the types of React props are accurately assigned?

Dealing with large datasets in a component can be challenging, but I have found a solution by creating a Proxy wrapper around arrays for repeated operations such as sorting. I am looking to ensure that when the data prop is passed into my component as an ...

Will synchronous programming on an Express server prevent other users from accessing the page simultaneously?

Currently working on a simple one-page web app that depends on loading weather data from a file. To avoid multiple HTTP requests for each visitor, I have a separate script refreshing the data periodically. In this particular instance, I am using fs.readFi ...

Learn how to create an animated refreshing icon in React when clicked

I have a refresh icon in my React app that utilizes Material UI. I want the icon to spin for a second after it is clicked, but I am unsure of how to achieve this. Despite attempting some solutions, none have been successful. const useStyles = makeStyles(( ...

Identifying the moment when the body scroll reaches the top or bottom of an element

I have been experimenting with javascript and jquery to determine when the window scroll reaches the top of a specific element. Although I have been trying different methods, I have yet to see any successful outcomes: fiddle: https://jsfiddle.net/jzhang17 ...

What could be the reason for the token being undefined on the client side?

I have built an ecommerce site using nextjs and mongoose, integrating a jwt token in a cookie for client-side authentication. However, when trying to retrieve the token from the cookie named OursiteJWT, I encountered issues with it being undefined: https: ...

Storing information in an array with automatic ID generation_incrementing

Here is an array in a specific format, however, there is no "ID" field available when the form is submitted. The requirement is to have an auto-generated ID assigned and saved in a JSON Array upon user submission of the form. With each form submission, t ...

Is there a way to display current data in angularJS based on the current time?

My database contains timestamps like 2016-12-30 00:30:10 which I retrieve using the $http module in Angular. Below is a snippet of my Angular code: angular .module('sampleApp') .controller('ReportCtrl', ReportCtrl) ...

What is the best way to update a page and retrieve fresh data from a service in Angular?

On my webpage, there is a table and two charts coming from three different controllers. I am looking for a way to refresh all of them simultaneously by clicking on a single refresh button. This will allow the data to be fetched from the webservice again an ...