从前整理过vuex,这篇是补充
最简单的vuex

多个组件共享状态时的vuex

初始化
vue create vuex-pro
mannul 装babel 其余不装
yarn serve启动项目
vuex基本使用
yarn add vuex
从前整理的文章,还是这些操作
mapstate
Bar.foo
import { mapState } from 'vuex'

getter
store中的计算属性
- 基本用法
准备数据
getter中的方法,找到剩余未作的事件数量
getters: {
remaining: state => {
return state.todos.filter(item => item.done === false).length
}
}
引入
import { mapGetters } from 'vuex'
使用


- getter返回函数
getter中的方法
mapGetters中也要改,剩下具体用法
mutations
-
一种推荐的写法
-
mutation要遵守vue的响应规则
需要在对象添加新属性时
Vue.set(obj, 'newProp', 123)
或者
state.obj = { ...state.obj, newProp: 123 } - 使用常量替代 Mutation 事件类型
大型项目使用,人少了就不用 -
mapmutations
可以使用mapmutations在组件中提交mutation,必须是同步的
action
可以包含异步操作
- 基本使用
store.js
actions: {
increment( {commit}, {num = 1}) {
setTimeout(() => {
commit({
type: 'increment',
num
})
}, 1000);
}
}
视图层
<button @click="asyncIncre">异步增加</button>
方法
asyncIncre () {
this.$store.dispatch('increment', {
num: 2
})
}
- 其余
mapActions可以取别名
可以结合Promise使用
可以结合async和await使用
可以调用异步api以及分发多重mutations
Module
将store分割成不同的模块。结合mobx里的store理解
即使写在模块里,action mutation getter也是全局的,除非加上namespaced: true,,调用的时候在视图层{{ $store.getters['foo/abc'] }}即可
购物车案例
vuex插件
自定义
内置logger
vuex-persistedstate -- 可以同步状态,刷新也不会丢失,类似于结合localStorage使用




