vue.jsvuejs3vue-props

Can props be accessed in beforecreated of vue?


In the vue docs, the part of "beforeCreate", I read the following:

Called immediately when the instance is initialized, after props resolution, before processing other options such as data() or computed.

Does this means that I can get props in beforeCreate hooks? if so, how can I get it? In my child component, I try like this to get the message passed by parent component, but failed.

export default {
  name: 'Child',
  props: ['message'],
  beforeCreate() {
    console.log(this.message)
  }
}

Solution

  • Please check the following snippet, looks like your code is fine:

    const app = Vue.createApp({
      data() {
        return {
          msg: 'aaa',
        };
      },
    })
    app.component('Child', {
      template: `<div>{{ message }}</div>`,
      props: ['message'],
      beforeCreate() {
        console.log('before create: ', this.message)
      }
    })
    app.mount('#demo')
    <script src="https://unpkg.com/vue@3.2.29/dist/vue.global.prod.js"></script>
    <div id="demo">
      <child :message="msg"></child>
    </div>