[Vuejs]-How to create reactive provide/inject

1👍

Options and composition API is combined, this may lead to the undetermined result. A is just reactive object with value property, can be created manually and then be passed by reference:

data: () => ({
  status: { value: null }
}),
provide() {
    return {
        PROVIDE_KEY_STATUS: this.status
    };
},
mounted() {
    this.status.value = 1;
    ...

In a child:

inject: {
    injStatus: { from: 'PROVIDE_KEY_STATUS' },
},
watch: { ['injStatus.value'](newVal, oldVal) {...}, ...

With composition API, this can be wrapped with composables:

const useProvideStatus = statusRef => provide('PROVIDE_KEY_STATUS', statusRef);

const useStatus = () => inject('PROVIDE_KEY_STATUS');

Leave a comment