Blog>
Snippets

Accessing Provided Data in Lifecycle Hooks

Demonstrate how to access provided data within component lifecycle hooks like mounted or created by injecting the data.
Vue.createApp({
  provide() {
    return {
      userData: 'User data provided by parent'
    };
  },
  mounted() {
    // Access the provided 'userData' in the mounted lifecycle hook
    console.log('Accessing userData in mounted:', this.userData);
  }
}).mount('#app');
In this piece of code, a Vue application is created with a 'provide' function that returns an object containing 'userData'. Inside the 'mounted' lifecycle hook, this 'userData' is accessed using 'this.userData' and logged to the console.
Vue.component('child-component', {
  inject: ['userData'],
  created() {
    // Access the injected 'userData' in the created lifecycle hook
    console.log('Accessing userData in created:', this.userData);
  }
});
This code defines a Vue component called 'child-component' which injects 'userData'. In the 'created' lifecycle hook, the component accesses the injected 'userData' and logs it to the console.
const app = Vue.createApp({
  data() {
    return {
      sharedData: 'Shared data across components'
    };
  }
});

app.provide('sharedData', app.config.globalProperties.sharedData);

app.component('example-component', {
  inject: ['sharedData'],
  mounted() {
    // The 'sharedData' is available and can be used within the mounted hook
    console.log('Accessing provided sharedData in mounted:', this.sharedData);
  }
});

app.mount('#app');
In this segment, a Vue application is augmented with a global data property called 'sharedData'. This data property is provided to all child components using 'app.provide'. The 'example-component' then injects 'sharedData', which it accesses within its 'mounted' lifecycle hook.