vuex state mutations的使用

146 阅读1分钟

index页面

 state: {
    count:0
  },
  //只有 mutations中定义的函数,才有权利修改state中的数据
  mutations: {
    add(state){
     //不要在 mutations函数中,执行异步操作
      // setTimeout(() => {
        state.count++
      // }, 1000);
    },
    addN(state,step){
      state.count += step
    },
    sub(state){
      state.count --
    },
    subN(state,step){
      state.count -=step
    }
  }

componets页面

<script>
import {mapState,mapMutations} from 'vuex'
export default {
  data(){
    return{};
  },
  computed:{
    ...mapState(['count'])
  },
  methods:{

     ...mapMutations(['sub','subN']),
         btnHandler1(){
           this.sub();
    },
    btnHandler2(){
      this.subN(3);
    }
  }
};
</script>

值在store中定义 函数也在store中定义 然后在组件页面中调用.