vuex五个核心概念
- state:vuex的基本数据,用来存储变量
- getters:从基本数据(state)派生的数据,相当于state的计算属性
- mutations:提交更新数据的方法,必须是同步的(如果需要异步使用action)。每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。
- actions:和mutation的功能大致相同,不同之处在于 ==》*Action 提交的是 mutation,而不是直接变更状态。 Action 可以包含任意异步操作
- modules:模块化vuex,可以让每一个模块拥有自己的state、mutation、action、getters,使得结构非常清晰,方便管理。

简述工作流程
- 在 vue 组件里面,通过 dispatch 来触发 actions 提交修改数据的操作。
- 然后再通过 actions 的 commit 来触发 mutations 来修改数据。
- mutations 接收到 commit 的请求,就会自动通过 Mutate 来修改 state
(数据中心里面的数据状态)里面的数据。 - 最后由 store 触发每一个调用它的组件的更新
辅助函数
mapState: 对state的对象进行二次计算,他可以简化我们代码,这样我们获取cartList,不用写this.$store.state.cartList一大串了,尤其对于我们组件中用到次数挺多的情况下,我们完全可以用mapState来代替。
1
2
3
4
5
6
7import { mapState } from 'vuex'
export default {
computed:mapState({
cartList:state => state.cartList,
getCartList:'cartList' //或者我们新定义一个参数,接受cartList,这样组件其他地方用到了,我们可以用this.getCartList来获取
})
}mapGetter:我们可以理解成他是和mapState一样,都是对state里面的参数进行计算,并返回相应的值,所以我们平常看到的mapState.mapGetters都是在computed属性里面,但是和mapState有点不同的是,mapState是仅对state里面的参数进行计算并返回,而mapGetters是对state参数派生出的属性进行计算缓存,比如计算state中cartList数组的长度或者对他的参数进行筛选
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15import { mapGetters} from 'vuex'
// getters.js
export default {
getCartListLen: state =>{
return state.cartList.length
}
}
// 组件
export default {
computed:{
mapGetters({
getLen:'getCartListLen'
}),
}
}mapMutation:写在methods里面,因为他触发的是方法
1
2
3
4
5
6
7
8
9import { mapMutations} from 'vuex'
export default {
methods:{
...mapMutations([
'add_cart', // 将 `this.add_cart()` 映射为 `this.$store.commit('add_cart')`
]),
}
}mapAction
1
2
3
4
5
6
7
8import { mapActions} from 'vuex'
export default {
methods:{
...mapActions([
'add_cart', // 将 `this.add_cart()` 映射为 `this.$store.dispatch('add_cart')`
]),
}
}
