记录工作中的点点滴滴

手把手教你怎么使用Vuex系列之开发计数器

手把手教你怎么使用Vuex系列之开发计数器

创建项目

我们先使用vue-cli创建一个基于webpack的项目。

1
2
3
4
5
6
7
vue init webpack vuex-step-demo
# 安装依赖
...
...
cd vuex-step-demo
npm install
npm run dev

访问 localhost:8080,会显示如下的页面:
Alt text

来看一下使用Vue命令行工具(vue-cli)创建的应用的目录结构:
Alt text

新建Store

在src目录下面新建store目录,store下新建store.js,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = {
count: 0
}
const mutations = {
increment (state) {
state.count++
},
decrement (state) {
state.count--
}
}
const actions = {
increment: ({ commit }) => commit('increment'),
decrement: ({ commit }) => commit('decrement'),
incrementIfOdd ({ commit, state }) {
if ((state.count + 1) % 2 === 0) {
commit('increment')
}
},
incrementAsync ({ commit }) {
return new Promise((resolve, reject) => {
setTimeout(() => {
commit('increment')
resolve()
}, 1000)
})
}
}
const getters = {
evenOrOdd: state => state.count % 2 === 0 ? 'even' : 'odd'
}
export default new Vuex.Store({
state,
getters,
actions,
mutations
})

展示计数器页面的组件Counter.vue:

1
2
3
4
5
6
7
8
9
10
<template>
<div id="app">
Clicked: {{ $store.state.count }} times, count is {{ evenOrOdd }}.
<button @click="increment">+</button>
<button @click="decrement">-</button>
<button @click="incrementIfOdd">Increment if odd</button>
<button @click="incrementAsync">Increment async</button>
</div>
</div>
</template>

js代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { mapGetters, mapActions } from 'vuex'
export default {
computed: mapGetters([
'evenOrOdd',
'recentHistory'
]),
methods: mapActions([
'increment',
'decrement',
'incrementIfOdd',
'incrementAsync'
])
}

在路由里添加 计数器的路由:
router/index.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import Vue from 'vue'
import Router from 'vue-router'
import Hello from '@/components/Hello'
import Counter from '@/components/Counter'
import App from '@/components/shopping-cart/App'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Hello',
component: Hello
},
{
path: '/counter',
name: 'Counter',
component: Counter
}
]
})

在main.js里引入store

1
2
3
4
5
6
7
8
9
import store from './store/store'
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: { App }
})

访问:http://localhost:8080/#/counter,回车则显示如下:
Alt text