Vue plugins are a good way to keep your components simple and small.  Once you are more familiar with Vue you’ll find that some components  need the same logic. For example in a component that watches an array  variable I often want to know what the added or removed value(s) is.  Instead of copy/pasting that code to other components or even projects  you can create a (set of) plugin(s) containing these methods and  expose/access them throughout the application.

So lets create a plugin ;) → full application link at the bottom.

The case → lets say we have a form where the user has a set of  checkboxes representing possible 🍕 toppings. Now we want to show a  message related to each topping when the user selects it. The problem is  that when we simply watch the array it will give us the complete  new/old array, not the added or removed value which we need to decide  what message to show.

Here it is only used in one place but you can imagine that throughout  the application you may need this functionality in other components as  well. So a plugin that exposes this functionality globally would be nice.

Create a folder helpers inside your application, or any other namespace that suits better for  the set of methods you want to expose. Next, create a new js file. In this case we call it general-helpers.js .  This wil be our plugin file containing the exposed set of functions.  For the array difference in our case it will look like this.

export default {
  install: (Vue) => {
    Vue.prototype.$helpers = {
      arrayDifference(arrayA, arrayB) {
        (arrayA.length < arrayB.length) && (arrayB = [arrayA, arrayA = arrayB][0]);

        return arrayA.filter((x) => {
          return arrayB.indexOf(x) < 0;
        });
      }
    };
  }
};

A Vue.js plugin should expose an install method. The method will be called with the Vueconstructor as the first argument. This gives us the chance to extend the Vue object and add a custom set of methods. There are some other things you can do as well as you see here in the docs. But we will simply add the$helpers object to the vue instance containing our methods.

This was the hardest part 😄 now we only need to install the plugin which can simply be done by importing the plugin file in your app.js and pass it to the Vue.use method.

import generalHelpers from './helpers/general-helpers.js'

Vue.use(generalHelpers);

Now you can simply access the method inside your components. 🎉

watch: {
  selectedToppings: function(newValue, oldValue) {
    let values = this.$helpers.arrayDifference(newValue, oldValue);

    if (newValue.length > oldValue.length) {
      values.forEach(value => {
        this.$emit('addTopping', value);
      });

      return;
    }

    values.forEach(value => {
      this.$emit('removeTopping', value);
    });
  }
}

That’s it. If you want to see the full application and test some things out, go ahead. (full application)