你需知道的Vue全家桶

vuex详细教程请转Vuex官网

一、知识点小结:

1.复合辅助函数
1
2
3
4
5
6
7
8
9
10
computed: {
localComputed () { /* ... */ },
// 使用对象展开运算符将此对象混入到外部对象中
...mapState({
// 映射 this.count 为 store.state.count
count: state => state.count, ① == ②
//计算属性的名称与 state 的子节点名称相同时
'count' ② == ①
})
}
2.Getters 接受 state 作为其第一个参数,也可以接受其他 getters 作为第二个参数
1
2
3
4
5
6
getters= {
// ...
doneTodosCount: (state, getters) => {
return getters.doneTodos.length
}
}
3.更改 Vuex 的 store 中的状态的唯一方法是提交 mutation,mutation 都是同步事务
1
2
3
4
5
6
7
8
9
// ...
mutations= {
increment (state, payload) {
state.count += payload.amount
}
}
store.commit('increment', {
amount: 10
})
4.Actions相当于异步mutation,Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象作为参数
1
2
3
4
5
6
7
8
9
10
11
// 假设 getData() 和 getOtherData() 返回的是 Promise
actions= {
async actionA ({ commit }) {
//触发mutation
commit('gotData', await getData())
},
async actionB ({ dispatch, commit }) {
await dispatch('actionA') // 等待 actionA 完成
commit('gotOtherData', await getOtherData())
}
}
5.Store可以复合Modules将 store 分割成模块,每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块
1
2
3
4
5
6
7
8
export default new Vuex.Store({
actions, //公用的actions
getters, //公用的getters
modules: {
cart, //拥有自己的 state、mutation、action、getter
products //拥有自己的 state、mutation、action、getter
},
})
  • 对于模块内部的 mutation 和 getter,接收的第一个参数是模块的局部状态对象。
  • 对于模块内部的 action,局部状态通过 context.state 暴露出来, 根节点状态则为 context.rootState
1
2
3
4
5
6
7
8
const moduleA = {
// ...
actions: {
incrementIfOddOnRootSum ({ state, commit, rootState }) {
//...
}
}
}
  • 对于模块内部的 getter,根节点状态会作为第三个参数暴露出来
1
2
3
4
5
6
7
8
const moduleA = {
// ...
getters: {
sumWithRootCount (state, getters, rootState) {
return state.count + rootState.count
}
}
}
添加插件,例如同步 websocket 数据源到 store
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
export default function createWebSocketPlugin (socket) {
return store => {
socket监听到后台触发的data改变时触发receiveData的mutation ①·
socket.on('data', data => {
store.commit('receiveData', data)
})
//store监听到mutation触发后发送socket到后台 ②
store.subscribe(mutation => {
if (mutation.type === 'UPDATE_DATA') {
socket.emit('update', mutation.payload)
}
})
}
}
const plugin = createWebSocketPlugin(socket)
const store = new Vuex.Store({
state,
mutations,
plugins: [plugin]
})
内置 Logger 插件

如果正在使用 vue-devtools,你可能不需要此插件

1
2
3
4
import createLogger from 'vuex/dist/logger'
const store = new Vuex.Store({
plugins: [createLogger()]
})
组件template中可以直接使用跟属性例如:$stroe
1
2
3
4
5
<template>
<div id="app">
Clicked: {{ $store.state.count }} times, count is {{ evenOrOdd }}.
</div>
</template>

二、项目实战

源码在github:vue-example,基于vue2+vue-router2+vuex2,不是我吹牛,vue看完我这个例子就够了,比官网的好懂