Blog>
Snippets

Sharing Functions through Provide/Inject

Provide a function from a parent component and show how to inject and use that function in child components to alter shared state.
Vue.component('parent-component', {
  provide() {
    return {
      changeSharedState: this.changeSharedState
    };
  },
  data() {
    return {
      sharedState: 'initial state'
    };
  },
  methods: {
    changeSharedState(newState) {
      this.sharedState = newState;
    }
  },
  template: `<div>
    <child-component></child-component>
    <p>Shared State: {{ sharedState }}</p>
  </div>`
});
In the parent component, a function 'changeSharedState' is provided, which allows modifying 'sharedState'. The data and provide properties ensure the function is accessible in child components through injection.
Vue.component('child-component', {
  inject: ['changeSharedState'],
  methods: {
    updateState() {
      this.changeSharedState('updated state');
    }
  },
  template: `<button @click="updateState">Change Shared State</button>`
});
In the child component, the function 'changeSharedState' is injected from the parent. A button is provided in the template to trigger the 'updateState' method, which calls the injected function to alter the shared state.