学习笔记Vue(二十三)——vuex mutation & action

一、mutation

直接在组件中修改vuex的state值在严格模式下是不允许的,需要通过mutation来对state中的值进行操作,不然会报错,提示你使用mutation。
mutations里可以放函数,通过在组件的methods里使用$store.commit(‘函数名’)来执行mutations里的函数。
还可以在commit的时候给mutations函数传参,写做一个对象的形式:
store.js

export default new Vuex.Store({
  //严格模式 在 开发环境开,在生产环境不开
  strict: process.env.NODE_ENV !== 'production',
  state: {
      name: 'grandmaz',
      age: 22,
      studentList: []
  },
  getters: {
  },
  mutations: {
    changeStudentList (state, {tempObj, name}){
	      state.studentList.push(tempObj);
	      state.name = name;
	    }
    }
  },
  actions: {
  }
})

组件:addStudent.vue

methods: {
     handleClick(){
         this.$store.commit('changeStudentList', {tempObj:tempObj, name: 'znn'});
     }
 }

使用mapMutations

mapMutations的使用方法和mapState、mapGetters没什么区别,由于mutations是方法,所以扩展在methods里:

        methods: {
            ...mapMutations(['changeStudentList']),
            handleClick(){
                const tempObj = {
                    name : this.name,
                    age: this.age,
                    id: +new Date()
                }
                this.changeStudentList({tempObj:tempObj, name: 'znn'});
            }
        }

二、action

mutations 里只能执行同步的操作,如果需要异步操作,则要使用actions,在actions中提交mutaitons,在组件中使用$store.dispatch()来执行actions。
store.js

export default new Vuex.Store({
  //严格模式 在 开发环境开,在生产环境不开
  strict: process.env.NODE_ENV !== 'production',
  state: {
      name: 'grandmaz',
      age: 22,
      studentList: []
  },
  getters: {
  },
  mutations: {
    changeStudentList (state, {tempObj, name}){
      state.studentList.push(tempObj);
      state.name = name;
    }
  },
  actions: {
    changeStudentList ({commit}, payload){
      //payload 传递的参数
      setTimeout(()=>{
          commit('changeStudentList',payload);
      },1000);
    }
  }
})

组件:addStudent.vue

methods: {
     ...mapMutations(['changeStudentList']),
     handleClick(){
         const tempObj = {
             name : this.name,
             age: this.age,
             id: +new Date()
         }
         this.$store.dispatch('changeStudentList',{tempObj:tempObj, name: 'znn'});
     }
 }

使用mapActions

mapActions和mapMutations用法类似:

        methods: {
            ...mapActions(['changeStudentList']),
            handleClick(){
                const tempObj = {
                    name : this.name,
                    age: this.age,
                    id: +new Date()
                }
                this.changeStudentList({tempObj:tempObj, name: 'znn'});
            }
        }

你可能感兴趣的:(Vue学习)