Leveraging props in the BeforeMount or Mounted hooks of VUE.JS

In one of my components, I have a property called kpi_kalite[] in the child component.

Within the parent component's mounted() method:

(The kpi_kalite array is defined in the data property of the parent component)

 axios.get(URL+ "/KPI/").then(response=>{

   console.log(JSON.parse(JSON.stringify(response.data)))

   this.kpi_kalite.push(response.data[0])

 })

I make a 'get request' in the parent component and add the response data to the kpi_kalite[] array (in the parent component).

Then, I pass this array as props to the child component.

However, when I try to log this.kpi_kalite in beforeMount or Mounted, it shows undefined.

 methods : {
     set_input(){

            console.log(this.kpi_kalite)
            for(const i in this.kpi_kalite){
                console.log(i)
                console.log(JSON.parse(JSON.stringify(this.kpi_kalite))) // output 
                                                                        //   "undefined"
       }
   }

},
beforeMount() {
    this.set_input()
}

The console output shows: undefined

Can anyone assist me? I need to access the parent component's data in the child component before the HTML-CSS is loaded.

Answer №1

LinusBorg wrote a post discussing the sequence of lifecycle hooks for parent and child components:

It all makes sense when you think about it logically.

  • The beforeCreate() and created() hooks of the parent component are executed first.
  • Next, the parent's template is rendered, leading to the creation of child components.
  • This triggers the beforeCreate() and created() hooks of the child components.
  • Subsequently, the child components are mounted to DOM elements, triggering their beforeMount() and mounted() hooks.
  • Finally, after the parent's template is complete, the parent component is mounted, invoking its beforeMount() and mounted() hooks.

END

You can find a helpful diagram here.

In Vue.js, child components are mounted before the parent component. This means that console.log(this.kpi_kalite) in the child component will not display data fetched from an axios call in the parent component until the child component is created and mounted. You need to ensure that the child component is rendered after the axios call completes to see the value of kpi_kalite from the axios response.

ParentComponent:

<ChildComponent v-if="renderChildComponent" :kpi_kalite="kpi_kalite" />

data() {
   return {
      kpi_kalite: [],
      renderChildComponent: false,
   };
},
mounted() {
   axios.get(URL+ "/KPI/").then(response=>{
      console.log(JSON.parse(JSON.stringify(response.data)))
      this.kpi_kalite.push(response.data[0])
      this.renderChildComponent = true;
   })
},

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 distinction between client-side and server-side onclick events

I am working on enhancing a composite control's client side functionality by recreating all methods in JavaScript. However, I am facing some issues: Is it possible to trigger the onclick event on the client side instead of the server side? The state ...

Can local storage be accessed within a function and utilized during the Windows.onload event?

I have an onclick function that dynamically returns 'x' and stores it in a div. However, after a page refresh, the dynamic div resets and the data is lost. To prevent this, I stored the data in local storage within the 'test' function a ...

Tips for accessing a composition function in VueJS from another composition

I've been diving into the new composition-api within VueJS and have encountered a problem that I need help with. I am seeking advice on how to effectively tackle this issue. Previously, when everything was vuex-based, dispatching an action to another ...

The JSON.stringify() method does not update the object that has been modified by an event

Below is the code snippet: //function triggered when columns are reordered dataTable.on('column-reorder', function (e, settings, details) { var userData = tableWidget.grid('userData'); console.log(userData); //userData object s ...

How can I efficiently update child states within a parent class using ReactJS?

Exploring the parent component class Root extends React.Component { constructor(props) { super(props); this.state = { word: Words, }; } c ...

What is the best way to generate an @ symbol using JavaScript?

When coding in Javascript, a challenge I am facing is creating a variable that includes the @ symbol in a string without it being misinterpreted as something else, especially when dealing with URLs. Does anyone have any suggestions on how to handle this ...

jquery events fail to trigger following the dynamic loading of new content

I have developed a voting system that utilizes images. When a user clicks on an image, it submits the vote and fades out before reloading using a PHP page. The issue I'm facing is that after the first submit, clicking on the images does not trigger an ...

Show a collection of elements containing attributes in JSX

I have a React component where I am displaying data from an array called pkgData: <div className="mainApp"> <div className="pkgsList"> {pkgData.map((p) => <h3 key={p.name}>{p.name}</h3> ...

Chromium based browsers are displaying varying values when using canvas.getimagedata()

Update: The solution is to enable willReadFrequently: true on the canvas in Chromium so that getImageData() will consistently return values. Please refer to the answer below for more details. Currently, I am working on a program that selects a pixel from ...

Disable ESLint's "no-undef" rule for a specific folder when using Jest

Currently, I am using jest for testing my api calls. In addition, I utilize eslint to validate my test codes. However, since jest does not require explicit definition of methods such as test() or expect(), when running eslint, I encounter errors like: ...

Updating is not happening with ng-repeat trackBy in the case of one-time binding

In an attempt to reduce the number of watchers in my AngularJS application, I am using both "track by" in ngRepeat and one-time bindings. For instance: Here is an example of my view: <div ng-repeat="item in items track by trackingId(item)"> {{ : ...

Tips on utilizing the useState hook for storing numerous key objects?

Currently, I am working with a candlestick chart for a cryptocurrency that displays data over different timeframes such as 1 minute and 30 minutes. Below is the code snippet that sets the initial state to show a 1-hour chart when a user first visits: const ...

An error message is displayed when attempting to retrieve a json response

After implementing my flask app, I noticed that the following code snippet is being returned: return json.dumps({'status': 'OK','url': 'www.blahg.com'}) Upon inspecting my javascript code, I found it to be structur ...

Difficulty in jQuery's clone() function: cloning an input element without its value

I have successfully implemented jquery's .clone() method, but I'm facing an issue where the value of the previous input field is also getting cloned along with it. How can I prevent this from happening? Below is my code snippet: function addrow ...

Nextjs is having trouble loading the Infogram script

Struggling to insert an Infogram into my project by pasting the script but it's not working as expected. All other scripts in _app.js are functioning properly, however, this particular script isn't loading the graphic even though it appears when ...

React SVG not displaying on page

I am facing an issue with displaying an SVG in my React application. Below is the code snippet: <svg className="svg-arrow"> <use xlinkHref="#svg-arrow" /> </svg> //styling .user-quickview .svg-arrow { fill: #fff; position: ...

Load texture using ImageUtils with callback in Canvas Renderer

Currently, I am utilizing three.js revision 53. While attempting to load a texture in Canvas Renderer (specifically on Win7) and incorporating a callback for the onLoad event, the texture fails to display. Surprisingly enough, removing the callback functi ...

There was an issue with the event handler: "Encountered an error as 'this.data()' is not recognized as

My HTML list contains links with unique data-… attributes: <ul id="list"> <li><a data-info="link1"> **** </a></li> <li><a data-info="link2">****</a></li> <li><a data-info="link3" ...

Send the chosen value from a dropdown menu to a PHP script

<style type="text/css"> form select { display:none; } form select.active { display:block; } </style> <script type="text/javascript"> window.onload = function () { var allElem = document. ...

Update the div content to completely replace it with fresh data using Ajax

I'm currently working on implementing a currency switcher feature for my website, allowing users to toggle between two different currencies. The site is a reservation platform with a booking form displayed on the left side and the booking details occu ...