Vuex mapState mapGetters mapMutations mapActions

Vuex mapState mapGetters mapMutations mapActions

在computed或methods中使用,在模板语法中可简化state调用声明

<template>
  <div>
    <select v-model="unit">
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>
    <button @click="increment(unit)">加</button>
    <button @click="decrement(unit)">减</button>
    <button @click="increOdd(unit)">奇数加</button>
    <button @click="decreAsync(unit)">异步减</button>
    <!-- <h1>{{ $store.state.count }}</h1> -->
    <!-- <h1>{{ $store.getters.bigCount }}</h1> -->
    <h1>{{count}}</h1>
    <h1>{{ bigCount }}</h1>
    <h1>{{ prop1 }}</h1>
    <h1>{{ prop2 }}</h1>
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";

export default {
  data: () => ({ unit: 1 }),
  computed:{
    // 对象写法
    // ...mapState({prop1:'prop1',p2:'prop2'}),
    // ...mapGetters({bigCount:'bigCount'})
    // 数组写法
    ...mapState(['count','prop1','prop2']),
    ...mapGetters(['bigCount'])
  },
  methods: {
    ...mapMutations({increment:'incre',decrement:'decre'}),
    ...mapActions({increOdd:'INCRE_ODD',decreAsync:'DECRE_ASYNC'})
  }
};
</script>

store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
// 注册Vuex插件
Vue.use(Vuex)

export default new Vuex.Store({
    // 修改数据的动作
    actions: {
        INCRE_ODD(context, payload) {
            context.state.count % 2 !== 0 && context.dispatch('INCRE_ASYNC', payload)
        },
        INCRE_ASYNC(context, payload) {
            setTimeout(() => {
                context.commit('incre', payload)
            }, 500);
        },
        DECRE_ASYNC(context, payload) {
            setTimeout(() => {
                context.commit('decre', payload)
            }, 500);
        }
    },
    // 操作数据的行为
    mutations: {
        incre(state, payload) {
            state.count += payload
        },
        decre(state, payload) {
            state.count -= payload
        }
    },
    // 初始化数据
    state: {
        count: 0,
        prop1:'prop1 value',
        prop2:'prop2 value'
    },
    getters:{
        bigCount(state){
            return state.count * 10
        }
    }
})
posted @ 2022-02-13 16:59  IslandZzzz  阅读(20)  评论(0编辑  收藏  举报