WoJ
WoJ

Reputation: 29977

When is a prop defined, equal to what was passed to the component?

I have some unreliable behaviour of my component to which a prop is passed that I want to debug:

<my-component :number="someNumber" />

number is made available in my-component via a standard prop: ["number"] declaration.

My question: at which point of the reactivity cycle is number defined to the value of someNumber in the parent?

Specifically, I need to make some actions when number has the correct value (I assume that it is undefined before that). I can do that in:

Which is the correct approach? (i.e. the one where number has the value that is passed to the component).


My current findings are that:

So my workaround will be to use both (with some checks against undefined) but it looks really shaky.

Upvotes: 0

Views: 98

Answers (1)

Michal Lev&#253;
Michal Lev&#253;

Reputation: 37763

It is available in the data() which happens before created. Literally only place where you can define some code to be executed by Vue where props are not available is beforeCreated lifecycle hook

Vue.component('my-component', {
  props: ["p"],
  data() {
    return {
      d: this.p
    }
  },
  created() {
    console.log("created:", this.p, this.d)
  },
  mounted() {
    console.log("mounted:", this.p, this.d)
  },
  template: `<div>{{ p }} {{ d }}</div>`
})

const vm = new Vue({
  el: '#app',
   data() {
    return {
      v: 10
    }
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"> 
  <my-component :p="v"></my-component>
</div>

Upvotes: 1

Related Questions