Creating a Plugin for Vue.js

Create a plugin which augments the Storage API with Vue.js to manage state

Tyrone Tudehope
Tyrone Tudehope: Blog

--

Plugins in Vue.js are very useful; they allow you inject global methods, instance methods, add directives and create mixins. For this example, we’ll be creating a basic state management plugin which stores and fetches data from the Storage API.

The idea is that when the app loads, we load a set of default data into localStorage (or sessionStorage), if the data already exists, the plugin will update itself with that data.

For example, if we had the following default data:

{
name: 'Default',
count: 10
}

and localStorage had just the name key stored with a value of Foobar, the plugin should update itself so that the actual data it contains is

{ 
name: 'Foobar',
count: 10
}

and LocalStorage should be updated to have a key of count with the value 10.

Changes to the data stored by the plugin should update localStorage.

Before we dive in, have a look at the finished plugin and its usage. Run the Fiddle, and add a few names to the list. When you rerun it, the data you captured should still be there. The same applies when names are removed.

Vue.use() requires that an install method is exposed. This method accepts the Vue object and anoptions object. The install method is where we can add any mixins, directives, etc. In our case, we need a mixin and an instance property:

We want to tell Vue that we would like to use this plugin, but we don’t want to configure it immediately. Therefore, we need to override the beforeCreate lifecycle hook to check if we’ve passed an instance of the plugin through to Vue when it was instantiated, like so:

In beforeCreate we define an instance property $storage which returns the plugin instance passed to Vue. All child components will also receive this property from their parent.

createStorage() is where we pass through an implementation of Storage, our desired initial state, and an optional flag to reset the state. It creates a new Vue instance with a data object created from the initial state passed to it, and watcher functions for each of the data props which update Storage for us. It also updates the data object with any data previously stored in the storage instance.

Because we’ve created an instance of Vue, all our data is already reactive. So we can make use of all the cool things Vue gives us, such as watchers, computed functions and reactive templates.

Plugins let you add global functionality to your Vue application. With this plugin we have wrapped the Storage API and provided access to it without the need to reference localStorage.

I recommend checking out the vuex and vue-router repositories for examples of much more complex plugins.

--

--