This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

Manage Vue.js State with Vuex and Nuxt

2:03 Vue.js lesson by

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

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

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

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 1:41] 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.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?