Recently, I try to use Vuex to do some small projects. After some studies, I find a better way for myself to understand and use it. Here, I just put them done in my blog for later reading. If you find any grammar mistakes or misleading opinions, please let me kown. Thank you.
define a store
First define a store. A store
should contain 4 parts, they are
- state
- mutaions
- actions
- getters
after define these 4 parts, combine them by using Vue.Store()
.
State
is an Object. It contains all the data information of your app. Each Vuex instance is just a single state tree.
mutations
are operations that actually mutates state. And state can only be changed by mutations. Each mutaion handler gets the entire state tree as the first argument, followed by additional payload arguments. Mutations must be synchronous and be recorded by plugins for debugging purposes
.
actions
are functions that causes side effects and handle your logical process . Unlike mutations
, you can involve asynchronous operations.
getters are functions
.
let’s see an counter example.
1 | import Vue from 'vue' |
The above example comes from https://github.com/vuejs/vuex. You can see that all the four parts are been written in one file, which is bad for big and complex projects. To avoid this, just split them, and then combine them together.
define entry
You may have an root element in your app. Just set the store and the view component to the root element. In this way , your store will be available in any place of your application.1
2
3
4
5
6
7
8
9import Vue from 'vue'
import Counter from './Counter.vue'
import store from './store'
new Vue({
el: '#app',
store,
render: h => h(Counter)
})
Then, you just need to include this file in your index.html. Shared.js
is common code that you extract by webpack.bundle.js
includes all the code that you need in this app.
1 | <body> |
write your view component
After defining the entry, We can begin write our component. Notice that you can use your Store
Object now.
Use $store.state.count
to get your state info. And by functions like mapGetters
and mapActions
,you can get the functions that you have just defined in store a moment ago.
1 | <template> |
run the app
We have just used ES2015 and vue, so it’s necessary to use webpack compiling all the code.
Actually, I am not very skilled in webpack. So I keep them down, and give some small introductions for later checking out.
1 | const webpack = require('webpack'); |
After make the webpack.config
,let’s start the server. Here, we can use express
to build a little server.
1 | const express = require('express') |
npm package opn
was used to force open the browser.