1
votes

I have 3 vue.js nested components: main, parent, child.

The parent component load basic data, the child is a simple countdown widget which needs just a data to be configured.

If I set the parent script with static data (IE deadline='2019-12-12') the child show the widget working nice, but if I use dynamic data it generate error.

I'm using computed to pass data to the child component and if I debug it using an alert I see 2 alerts: undefined and then the correct date.

The issue is the first computed data (undefined) crash the widget, so how to create child component using updated (loaded) data?

Parent template:

<template>
   <div>
    <flip-countdown :deadline=deadline></flip-countdown>
   </div>
</template>

Parent Script: it needs to be fixed

export default {
    components: {FlipCountdown},

    props: ['event'],

    computed: {

        deadline: function () {
            if (typeof(this.event.date)!="undefined") {
                //alert(this.event.date)
                return this.event.date;
            } else {
                return "2019-05-21 00:00:00";
            }
        },
    },

Child template: it works

<template>
  <div>
      <flip-countdown :deadline="deadline"></flip-countdown>
  </div>
</template>
1
Your parent template and child template look exactly the same, except that you forgot the double qoutes in deadline=deadline (should be deadline="deadline"). Also, in order to prevent errors when deadline is wrong, you could just add v-if="deadline" to your <flip-countdown> - Constantin Groß
Thanks, the directive v-if="deadline" it's a good fix. I used two very similar components to have a complete component in just one place. Btw I'll change the names to avoid mistakes. Using directive v-if I'll remove all computed values. Thanks for suggestion. - Uncoke

1 Answers

0
votes

Your parent component passes the deadline to its child component before the mounted lifecycle hook fires. Your child component sets its deadline with the initial value of undefined.

You should make deadline a computed property in child component:

computed: {
  internalDeadline() {
    return this.deadline; // comming from props
  }
}

Then you can use internalDeadline in child.


Alternatively, you could wait to render the child component until deadline is defined:

<flip-countdown v-if="deadline !== undefined" :deadline="deadline"></flip-countdown>