Home > Software engineering >  Access to props in child component mounted
Access to props in child component mounted

Time:08-01

From what I understand, because the child component is mounted first then the parent component is mounted, when we try to access props in the child component's mounted period, we will get null.

However, I encountered a situation where props are accessed in the child component's mounted period. It was when the parent component's v-model was an array.

This is the parent component example.

<example-input
  v-model="arr[i]"
/>
...
<script>
  ...
  data () {
    return {
      arr = ['a', 'b', 'c']
    }
  }
</script>

This is the child component example.

export default {
  props: value,
  ...
  mounted () {
    console.log(this.value) <<< results comes in!
  }
}

When I run it, each value in arr is printed. I am quite confused about this finding.

I tried to search for cases similar to mine, but currently, I am in vain. How come props are accessed in the child component's mounted period? Please help me out with this!

CodePudding user response:

@codingEffort console.log() is passed a reference to the object, so the value in the console will update as the object updates. Objects and Arrays are pass by reference in Javascript. To see it's true value you can coerce it to a string (which is pass by value) in your mounted call,

mounted () {
  console.log('value as string:', JSON.stringify(value))
}

OR, create a new object and so a new reference,

mounted () {
  console.log('value as array:', JSON.parse(JSON.stringify(value)))
}

CodePudding user response:

I am not sure what issue you are facing, but as we are passing prop from data property, It should be available in the child mounted with irresepect to type (string or array).

Live Demo (Here string type is accessing in the child mounted) :

Vue.component('child', {
  props: ['childmsg'],
  template: '<h3>{{ childmsg }}</h3>',
  mounted() {
    console.log('child mounted call', this.childmsg);
  }
});

var app = new Vue({
  el: '#app',
  mounted() {
    console.log('parent mounted call');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <child childmsg="This is a child message">
  </child>
</div>

  • Related