Nuxt/examples/vuex-store-2/README.md

95 lines
1.8 KiB
Markdown
Raw Normal View History

2016-12-30 09:11:55 +00:00
# Nuxt.js with Vuex 2
2016-12-26 14:55:00 +00:00
> Using a store to manage the state is important to every big application, that's why nuxt.js implement Vuex in its core.
2016-12-30 09:11:55 +00:00
> Alternative way of creating a store modularly.
2016-12-26 14:55:00 +00:00
## Activating the store
2016-12-30 09:11:55 +00:00
Nuxt.js will look for the `./store/` directory, if it exists, its will import and use Vuex. If there is no `./store/index.js` file that returns a store, Nuxt.js will go through all files of the `./store/` directory and create a store with a module for each file (`./store/index.js` being "root" module).
2016-12-26 14:55:00 +00:00
## Create the store folder
Let's create a file `store/index.js`:
```js
2016-12-30 09:11:55 +00:00
export const state = { counter: 0 }
export const mutations = {
increment (state) {
state.counter++
}
}
```
2016-12-26 14:55:00 +00:00
2016-12-30 09:11:55 +00:00
and
`store/todos.js`:
2016-12-26 14:55:00 +00:00
2016-12-30 09:11:55 +00:00
```js
export const state = {
list: []
}
export const mutations = {
add (state, { text }) {
state.list.push({
text,
done: false
})
2016-12-26 14:55:00 +00:00
},
2016-12-30 09:11:55 +00:00
delete (state, { todo }) {
state.list.splice(state.list.indexOf(todo), 1)
},
toggle (state, { todo }) {
todo.done = !todo.done
}
}
2016-12-26 14:55:00 +00:00
```
> We don't need to install `Vuex` since it's shipped with nuxt.js
## Voilà !
We can now use `this.$store` inside our `.vue` files.
```html
<template>
<button @click="$store.commit('increment')">{{ $store.state.counter }}</button>
</template>
```
2016-12-30 09:11:55 +00:00
The store will be as such:
2016-12-26 14:55:00 +00:00
```js
2016-12-30 09:11:55 +00:00
new Vuex.Store({
state: { counter: 0 },
mutations: {
increment (state) {
state.counter++
}
},
modules: {
todos: {
state: {
list: []
},
mutations: {
add (state, { text }) {
state.list.push({
text,
done: false
})
},
delete (state, { todo }) {
state.list.splice(state.list.indexOf(todo), 1)
},
toggle (state, { todo }) {
todo.done = !todo.done
}
}
2016-12-26 14:55:00 +00:00
}
}
2016-12-30 09:11:55 +00:00
})
2016-12-26 14:55:00 +00:00
```