前端大纲---mutation与actions区别

95 阅读1分钟

image.png

image.png

image.png

image.png

image.png

image.png

  • mapState
   computed: {
        ...mapState({
          add: state => state.add,
          counts: state => state.counts
        })
    },
    mounted() {
      console.log(this.add); // 打印出 0
      console.log(this.counts); // 打印 0 
    }
  ...mapState([    'add',    'counts'  ])
  • mapMutations
  methods: {
      test() {
        // 使用 mapMutations 调用方式如下:
        Promise.all([this.ADD(1)]).then(() => {
          console.log(this);
        });
      },
      /*
      // mapMutations 使用方法1
      ...mapMutations(['ADD']), // 会将 this.ADD 映射成 this.$store.commit('ADD') 
      */
      // mapMutations 使用方法2
      ...mapMutations({
        'ADD': 'ADD'
      })
    }
  • mapActions
 import { mapActions } from 'vuex';
 test() {
        // 调用
        Promise.all([this.commonActionGet(['getPower', {}])]).then((res) => {

        });
      },
      // mapActions 使用方法一 将 this.commonActionGet() 映射为 this.$store.dispatch('commonActionGet')
      ...mapActions(['commonActionGet', 'commonActionGetJSON', 'commonActionPost', 'commonActionPostJSON'])
      /*
       // 第二种方式
       ...mapActions({
         'commonActionGet': 'commonActionGet',
         'commonActionGetJSON': 'commonActionGetJSON',
         'commonActionPost': 'commonActionPost',
         'commonActionPostJSON': 'commonActionPostJSON'
       })
      */
  • vuex 为什么不能直接改变值,而是通过 mutation

image.png

vuex 更改state 是 dispatch 给 action,action 再 commit 给 mutation,这样实现了单向数据改动 区别普通双向绑定