This Lesson is for Members

Subscribe today and get access to all lessons! Plus direct HD download for offline use, enhances transcripts, member comment forums, and iTunes "podcast" RSS feed. Level up your skills now!

Unlock This Lesson

Already subscribed? Sign In


    Add options to a Vuex plugin using TypeScript

    Alex Jover MoralesAlex Jover Morales

    In some cases we may want to pass some options to a Vuex plugin, in order to make it more customizable. This lessons shows how can you make a Vuex plugin accept a persist parameter in order to save the state to the localStorage in TypeScript



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson


    The way it's done right now we cannot pass any parameter to the history plugin, and we want to pass a persist parameter to save the state in the local storage. For that let's go to the plugin file, and what we need to do is to use a higher other function to run the plugin function. Then we can pass an options parameter. We want to type it.

    Let's say there's a plugin options types, and then go to types.ds file, and let's try the start options typing here. It will have an optional persist property which is a bullet. Then after the plugin file, import the plugin options type. For the persistents the first thing the plugin has to do is load the state from local storage.

    For that let's try the load mutation that will set the state.history to the local storage item, and when we read it, using localstorage.getitem function, we will get a string. So we'll need to use this json. first and provide also a default string with an array for the first load when the item goes into assist.

    At this point we can call the mutation right after registering the module by using Of course, we will not do this only when the options.persist parameter is true. Let's wrap it with indecipherable 1:31 condition. The same down here.

    When the options parameters is true and we have the mutation to the history, then we want to update it in the local storage by using localstorage.setitem with the item key and the payload. In this case we have to use the json.stringify to convert it into string. We haven't tethered the history state to the root state, and now is a good time to do it.

    Go to the types file and add history colon history state to the root state. Then we see it in the inventory sense back here. We have to set up the history, which is the module and the indecipherable 2:20 history which is the array. The only thing left now is to go to the index file where we have the store and pass a persist parameter to the history plugin.

    If we try this out, let's trigger some mutations. If we inspect the state, we see that some mutations have been added. Now we reload the page, and we'll see all the histories back there.