还不知道vue中vuex如何使用?点击下面链接 链接:简单demo详细讲解
- Demo Github地址 :github.com/babybrother…
复习vuex工作原理
graph LR
A[客户端] -- 事件调用 dispatch --> B((Action))
C(State) -- state修改 render重新渲染 --> A
B -- commit一个type类型 --> D{Mutation}
D -- 匹配对应type操作state --> C
vuex五大核心 1.State 2.Getters 3.Mutations 4.Actions 5.Module 我们项目中需要的都是:state、getters、mutations、actions里面的东西 调用方法和使用的位置也是有区别的分别是 不过vuex给我们提供了辅助函数:mapState , mapMutations , mapActions , mapGetters
| 调用 | 方法 | 辅助函数 |
|---|---|---|
| state | this.$store.state. xxx | mapState |
| getters | this.$store.getters. xxx | mapGetters |
| mutations | this.$store.cmmit((xxx) | mapMutations |
| actions | this.$store.dispatch(xxx ) | mapActions |
==注意== mapState和mapGetter的使用只能在computed计算属性中, mapMutations和mapActions使用的时候只能在methods中调用否则报错
如何实际使用辅助函数?
<script>
import { mapState , mapMutations , mapActions , mapGetters } from 'vuex';
export default {
data(){
return{
}
},
computed:{
...mapState({
counts:(state) => state.count
}),
//mapState就等于下面这个
// counts(){
// return this.$store.state.count
// },
...mapGetters({
getternum:'doneTodos'
}),
//mapGetters就等于下面的这个
// getternum(){
// return this.$store.getters.doneTodos
// }
},
methods:{
...mapMutations({
addnum:'addNum'
}),
addnum1(){
this.addnum()
},
//mapMutations就等于下面的这个
// addnum1(){
// this.$store.commit('addNum')
// },
...mapActions({
actionnum:'actionNumAdd'
}),
actionnum6(){
this.actionnum()
},
//mapActions就等于下面的这个
// actionnum6(){
// this.$store.dispatch('actionNumAdd')
// }
}
}
</script>
辅助函数总结 vuex中的 mapState , mapMutations , mapActions , mapGetters 辅助函数 看上面的例子其实差不多, 当项目场景中我们需要大量的调用state中的值和触发多个actions的时候,我们还得写大量重复的代码,这时候辅助函数的作用就体现出来了,其实就是vuex的一个语法糖,是代码更简洁更优雅。 深入学习vuex状态管理的拆分及模块化处理
-
Demo Github地址:github.com/babybrother…