2

I am trying to pass data using provide and inject but the injected data is not reactive, can any help me to make it reactive.

//Parent.vue
<template>
 {{ParentName}}
</template>

<script>
export default {
  data(){
    return{
      ParentName: 'Initial Value'
    }
  }
  provide() {
   return {
     name: this.ParentName,
    };
  },
}
</script>

I am changing the 'ParentName' after 3 sec using mounted hook'

  mounted() {
    setTimeout(() => {
      this.ParentName = "New Name";
    }, 3000);
  },

In child component, i am injecting the value

//Child.vue
<template>
 {{name}}
</template>

<script>
export default {
  inject:['name']
}
</script>

But I am getting the injected name as 'Initial Value', not getting the updated value as "New Name" after 3 sec.

2 Answers 2

4

The provide/inject are not reactive by default. As suggested in the VUE documenation to make provide reactive we have to watch for any changes with computed. In the parent component you can do the following:

provide() {
return {
  name: computed(() => this.ParentName)
}

Then in the child simply inject that and it should work. For reference: https://v3.vuejs.org/guide/component-provide-inject.html#working-with-reactivity

Sign up to request clarification or add additional context in comments.

Comments

1

Also, if you want to update the provided value from a child component you need to update the computed property as follows:

provide() {
return {
 name: computed({
  get: () => this.ParentName,
  set: (value) => {this.ParentName = value}
 })
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.