注意: 只能通过 mutations里的函数才能修改 state 中的数据

第一种方法:

const store = new Vuex.Store({
  state:{
	count:0
  },
  mutations:{
	add(state){
	  state.count++
	}
  }
})
methods:{
    addnum() {
      this.$store.commit('add')
    }
}

注意: mutations里不能包含异步操作。

如果组件之间需要传递参数

const store = new Vuex.Store({
  state:{
	count:0
  },
  mutations:{
	add(state,step){
	  state.count +=step
	}
  }
}) 
methods:{
    addnum() {
      this.$store.commit('add',3)
    }
}
第二种方式:
import {mapMutations} from 'vuex'

  

mutations: {
  add(state) {
    state.count++
  },
  sub(state) {
    state.count--
  },
  addN(state, step) {
    state.count += step
  },
  subN(state, step) {
    state.count -= step
  }
},

  

import { mapState,mapMutations } from 'vuex'
computed:{
  ...mapState(['count'])
},
methods:{
  ...mapMutations(['sub','subN']),
  decrement(){
    this.sub()
  },
  decrementN(){
    this.subN(5)
  }
}

  

posted on 2021-04-18 19:24  大橙子最美丽  阅读(33)  评论(0编辑  收藏  举报