[Vuejs]-VueJs Nested props coming through undefined

2👍

It actually works fine without the watcher.

new Vue({
  el: '#app',
  data: {
    event: undefined
  },
  components: {
    subC: {
      props: ['event'],

      data() {
        return {
          regFields: []
        }
      },

      created() {
        this.regFields = this.event.registration_fields // Undefined here!
      }
    }
  },
  mounted() {
    setTimeout(() => {
      this.event = {
        registration_fields: [1, 3]
      };
    }, 800);
  }
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="app">
  <sub-c v-if="event" :event="event" inline-template>
    <div>
      {{regFields}}
    </div>
  </sub-c>
</div>

If, as Belmin Bedak suggests in the comment below, event is populated asynchronously, it comes in as undefined because it’s undefined. In that case, you need a watcher, or, somewhat more elegantly, use a computed:

new Vue({
  el: '#app',
  data: {
    event: {}
  },
  components: {
    subC: {
      props: ['event'],
      computed: {
        regFields() {
          return this.event.registration_fields;
        }
      }
    }
  },
  // delay proper population
  mounted() {
    setTimeout(() => { this.event = {registration_fields: [1,2,3]}; }, 800);
  }
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="app">
  <sub-c :event="event" inline-template>
    <div>
      {{regFields}}
    </div>
  </sub-c>
</div>
👤Roy J

Leave a comment