Alex.Party

Vuejs Dependency Injection - 2 Way Provide/Inject Data Binding

This post is a secret! Read more about RSS Club.

(This post was originally published on CodePen, but I’m putting it here. Enjoy!)

This is a follow up post to my previous post about Vuejs and Dependency Injection

In my previous post, I described a couple of ways to use provide and inject in Vue components. In this post I’m going to cover how to use provide/inject reactively. This method is not recommended, and we will go over some pros and cons of this method.

Demo

First, let’s make a property thing in a parent component have 2 way data binding to a nested child using provide and inject

Explanation

In the parent component we have a property called thing. Our methods and provide sections look like this:

export default {
// ...
  methods: {
    getThing: function() {
      return this.thing;
    },
    setThing: function(data) {
      this.thing = data;
    },
  },
  provide: function() {
    return {
        getThing:this.getThing,
        setThing:this.setThing
    }
  },
// ...
}

When you type into either of the 2 text boxes in the above example, it updates. This is what we want.

In this example, our parent component is providing 2 functions to it’s children. Because of the way that Javascript scoping works, when these functions are used, they will always refer to the values in the parent component.

To use this in our nested component, we need to make a computed property. Doing this, Vue will update the values on changes. Our nested components computed and inject sections are as follows:

export default {
// ...
  computed:{
    thing:{
      get:function(){
        return this.getThing()
      },
      set:function(d){
        this.setThing(d)
      },
    }
  },
  inject: ["getThing","setThing"],
// ...
}

In our computed section, all we are doing is making calls to our injected functions.

If you attempt to directly bind the injected values to get and set this will only result in thing showing up as an object, and not as a computed value.

Pros and Cons

There are some good and bad trade offs about this code pattern.

Pros

Cons

Conclusion

provide and inject can be used for two way data binding, but it is not recommended for every day projects. However, there may come a time when you realize that you need this, and hopefully you will find this information useful.

Edit: Thanks to The official Vuejs Podcast for the shout out. Watch my adventures as I try to make a blog over at Alex.party or follow me on twitter: @fimion