Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 611
BS100 Avatar asked Sep 20 '25 10:09

BS100


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

like image 76
tony19 Avatar answered Sep 22 '25 06:09

tony19