Is it possible to watch injected property

Viewed 3721

I am building an application which is using Vue 3 and I am providing a property in a parent component which I am subsequently injecting into multiple child components. Is there any way for a component which gets injected with this property to watch it for changes?

The parent component looks something like:

<template>
  <child-component/>
  <other-child-component @client-update="update_client" />
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      client: {}
    }
  },
  methods: {
    update_client(client) {
      this.client = client
    }
  },
  provide() {
    return {
      client: this.client
    }
  },
}
</script>

The child component looks like:

<script>
export default {
  name: 'ChildComponent',
  inject: ['client'],
  watch: {
    client(new_client, old_client) {
      console.log('new client: ', new_client);
    }
  }
}
</script>

I am trying to accomplish that when the provided variable gets updated in the parent the children components where its being injected should get notified. For some reason the client watch method is not getting called when client gets updated.

Is there a better way of accomplishing this?

Update

After further testing I see that there is a bigger issue here, in the child component even after the client has been updated in the parent, the client property remains the original empty object and does not get updated. Since the provided property is reactive all places it is injected should automatically be updated.

5 Answers

Update

When using the Object API reactive definition (data(){return{client:{}}), even though the variable is reactive within the component, the injected value will be static. This is because provide will set it to the value that it is initially set to. To have the reactivity work, you will need to wrap it in a computed

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

docs: https://vuejs.org/guide/components/provide-inject.html#working-with-reactivity


You may also need to use deep for your watch

Example:

<script>
  export default {
    name: 'ChildComponent',
    inject: ['client'],
    watch: {
      client: {
        handler: (new_client, old_client) => {
          console.log('new client: ', new_client);
        },
        deep: true
      }
    }
  }
</script>

As described in official documentation ( https://v2.vuejs.org/v2/api/#provide-inject ), by default, provide and inject bindings are not reactive. But if you pass down an observed object, properties on that object remain reactive.

For objects, Vue cannot detect property addition or deletion. So the problem in your code might be here:

  data() {
    return {
      client: {}
    }
  },

Since you change the client property of this object ( this.client.client = client ), you should declare this key in data, like this:

  data() {
    return {
      client: { client: null }
    }
  },

Now it becomes reactive.

I did a code sandbox reproducing your code watching an injected property: https://codesandbox.io/s/vue-inject-watch-ffh2b

For some reason the only way I got this to work was by only updating properties of the initial injected object instead of replacing the whole object. I also was not able to get watch working with the injected property despite setting deep: true.

Updated parent component:

<template>
  <child-component/>
  <other-child-component @client-update="update_client" />
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      client: {}
    }
  },
  methods: {
    update_client(client) {
      this.client.client = client
    }
  },
  provide() {
    return {
      client: this.client
    }
  },
}
</script>

Updated child component:

<template>
  <button @click="get_client">Get client</button>
</template>
<script>
export default {
  name: 'ChildComponent',
  inject: ['client'],
  methods: {
    get_client() {
      console.log('updated client: ', client);
    }
  }
}
</script>

create a new value and reference the value from inject into it

inject: ['client'],
data: () => ({
  value: null,
}),
created() {
  this.value = this.client;
},
watch: {
  value: {
    handler() {
      /* ... */
    },
    deep: true,
  }
}

Now you can watch the value.

Note: "inject" must be an object

I ran into the same issue. But i just had to look more closely for details in the docs to make it work. In the end everything worked fine for me.

I built a vue plugin providing a Map together with some function as a readonly ref. Then it starts changing the Map contents once a second:

plugin.js

    import { ref, readonly } from 'vue';

    const rRuns = ref( new Map() );
    let time = 0;
    
    export default
    {
      install(app, defFile)
      {
        ...
      
        app.provide( "runs", readonly(
        { ref: rRuns,
          get: (e) => rRuns.value.get( e ),
          locationNames: () => rRuns.value.keys(),
          size: () => rRuns.value.size,
        } ) );
    
        ...
        
        setInterval( () => 
          { time++;
            const key = (time * 7) % 10;
            console.log("  runs update", key, time);
            rRuns.value.set( key.toString(), time )
          }, 1000);
          console.log("  time Interval start" );
      }
    }

main.js:

    import { createApp } from 'vue'
    import App from './App.vue'
    
    import plugin from 'plugin.js'; 
    
    const app = createApp(App);
    app.config.unwrapInjectedRef = true;
    app.use(game, 'gamedefs.json');
    app.mount('#app');

runs.vue:

    <template>
      <h1>Runs:</h1>
      <p v-if="!runs.size()">&lt; no runs &gt;</p>
      <p v-else>runs: {{ runs.size() }}</p>
      <button v-for="r of runs.locationNames()" :key="r" @click="display( r )">[{{ r }}]</button>
    </template>
    
    <script>
    export default {
      name: 'Runs',
    
      inject: 
      { 
        runs: { from: 'runs' },
      },
    
      watch:
      { 
        'runs.ref':
        {
          handler( v )
          {
            console.log("runs.ref watch", v );
          },
          immediate: true,
          deep: true,
        },
      },
    }
    </script>
Related