vuex的语法糖-辅助函数mapState , mapMutations , mapActions , mapGetters

还不知道vue中vuex如何使用?点击下面连接 连接:简单demo详细讲解javascript

复习vuex工做原理vue

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 , mapGettersjava

调用 方法 辅助函数
state this.$store.state. xxx mapState
getters this.$store.getters. xxx mapGetters
mutations this.$store.cmmit((xxx) mapMutations
actions this.$store.dispatch(xxx ) mapActions

==注意== mapStatemapGetter的使用只能在computed计算属性中, mapMutationsmapActions使用的时候只能在methods中调用不然报错git


如何实际使用辅助函数?github

<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状态管理的拆分及模块化处理vuex

相关文章
相关标签/搜索