State Link to heading

获取State中的值的三种方法

  1. 直接在模板里面写
<p>{{ $store.state.count }}</p>
  1. 通过计算属性
computed: {
  count(){
    return this.$store.state.count
  }
}
  1. 通过mapstate
computed: mapState(['count'])

Mutations Link to heading

  1. 直接写在模板里面(不传值)
<button @click="$store.commit('add')">+</button>
  1. 通过mapmutations(推荐,传值不传值都可以使用)
const mutations = {
  add(state){
    state.count++;
  },
  reduce(state,n){
    state.count-=n;
  }
}
methods: {
	...mapMutations(['reduce','add'])
}
<button @click="add()">+</button>
<button @click="reduce(5)">-</button>

getters Link to heading

  1. 一般写法
const getters = {
  count : state => state.count+=100
}
computed: {
  ...mapState(['count']),
  count(){
    return this.$store.getters.count
  }
}
  1. 简写
const getters = {
  count : state => state.count+=100
}
computed: {
    ...mapState(['count']),
    ...mapGetters(['count'])
  }

actions Link to heading

methods: {
  ...mapActions(['addAction','reduceAction'])
}
<button @click="addAction">+</button>
<button @click="reduceAction">-</button>
const actions = {
  addAction({commit}){
    commit('add');
    setTimeout(()=>{commit('reduce',3)},2000);
    console.log('我比reduce提前执行');
  },
  reduceAction(context){
    context.commit('reduce',5);
    setTimeout(()=>{context.commit('add')},2000);
    console.log('我比reduce提前执行');
  }
}