Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Manage Vue.js State with Vuex and Nuxt

    John LindquistJohn Lindquist

    Most applications require state to be shared across the application. In the case of Nuxt, you'll share state across pages. Nuxt integrates easily with Vuex by simply adding JavaScript files in the store directory. This lesson walks you through setting up a basic store and using it in your template



    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




    To add a store to our project we'll add Vuex by creating a directory called Store and putting a file called index.js inside of there. You'll see that here -- storeIndex. Then I can export a const called state from this file. Then on this state I'll just say a counter has a value of zero.

    From here I can display this counter in my index.view by adding a script part of our view file and export default. This is an object and this object has a property called computed. Inside this computed I'm going to use what's called mapState from Vuex. I'll grab mapState and I'm going to spread it right away.

    This is the object spread, because mapState returns an object and I want it to merge with this computed object. I'll mapState where the counter is a function that takes in the state and gives me the state.counter.

    If this looks weird, don't worry, because the pattern will essentially be a bunch of these, where you're telling the thing on the left that I want this thing off of the state. Then each of these are merged into computed by this object spread.

    I'll delete all of them, because I only need the counter, which is mapped to the state.counter. Then I can go ahead and drop that counter inside of here by saying counter. I'll hit Save and if nothing appears here and you try and reload and nothing happens, you'll probably have to restart your dev server here.

    I control-C'd out of that and inaudible dev again. That's because we added a file which we're importing, which isn't always picked up by dev servers. We didn't do anything wrong in here, it's just that the dev server didn't pick up the fact that we added that file.

    Now, you'll see that zero, which is this state counter zero mapped into counter, because we're plucking it off of state here and then displayed in our counter.