vuex-Actions的用法

Action 类似于 mutation,不同在于:

Action 提交的是 mutation,而不是直接变更状态. Action 是异步的,mutation是同步的。

沿用vuex学习---简介的案例:这里是加10 减1

1.在store.js 中 代码为:

import Vue from 'vue'
import Vuex from 'vuex'
 
//使用vuex模块
Vue.use(Vuex);
 
//声明静态常量为4
const state = {
  count : 4
};
 
const mutations = {
  add(state,n){
    state.count +=n.a;
  },
  sub(state){
    state.count--;
  }
};
 
const actions = {
  //2种书写方式
  addplus(context){ //可以理解为代表了整个的context
    context.commit('add',{a:10})
  },
  subplus({commit}){
    commit('sub');
  }

};
 
//导出一个模块
export default new Vuex.Store({
  state,
  mutations,
  actions
})

2.在App.vue中 代码如下:

<template>
  <div id= "app" >
    <div id= "appaaa" >
     <h1>这是vuex的示例</h1>
 
     <p>组件内部count{{count}}</p>
     <p>
       <button @click = "addplus" >+</button>
       <button @click = "subplus" >-</button>
     </p>
     </p>
 
   </div>
  </div>
</template>
 
<script>
//引入mapGetters
import {mapState,mapMutations,mapGetters,mapActions} from 'vuex'
export default {
  name: 'app' ,
  data(){
    return {
      
    }
  },
  computed:{
    ...mapState([
      "count"
      ]),
  },
  methods:{
    ...mapActions([
       "addplus" ,
       "subplus"
      ])
  }
 
}
</script>
 
<style>
 
</style>

猜你喜欢

转载自www.cnblogs.com/web-chuanfa/p/9162451.html