Vue3 is it possible to change the data given by provide->inject from child's end?

Viewed 1973

As written in the subject,

in vue,

provide is used for passing data from parent to child.

and child element gets the data by inject.

as @emit does, is it also possible to modify data given by "provide" in child element?

Thank you.

1 Answers

Yes, a component could provide a ref that gets updated by a descendant that injects it:

// App.vue
export default {
  setup() {
    const counter = ref(0)
    provide('counter', counter)
  }
}

// ComponentA.vue
export default {
  setup() {
    const counter = inject('counter')

    return {
      counter,
      increment: () => counter.value++  // updates App.counter
    }
  }
}

demo 1

However, the Vue docs recommend also provide-ing an update method, keeping the mutation and state co-located:

// App.vue
export default {
  setup() {
    const counter = ref(0)
    provide('counter', counter)
    provide('increment', () => counter.value++)
  }
}

// ComponentA.vue
export default {
  setup() {
    return {
      counter: inject('counter'),
      increment: inject('increment'),
    }
  }
}

demo 2

Related