状态管理Vuex中5个重要的概念:State、Getter、Mutation、Action、Mudule

State:用于维护所有引用层的状态,并确保应用中只有唯一的数据源

组件中可以直接使用$store.state.count(store已经被注册到实例中),也可以先用mapState辅助函数将其映射下来

Getter:维护由State派生的一些状态,这些状态随State状态的变化而变化,类似computed属性,会被缓存

组件中可以直接使用$store.getters.tenTimesCount,也可以先用mapGetters辅助函数将其映射下来

Mutation:提供修改State的方法

组件中可以直接使用$store.commit来提交mutation

Action:类似Mutation,但不能直接修改状态,只能通过提交mutation来修改,可以包含异步操作

组件中可以直接使用$store.dispatch来分发action

Module:允许将store分割成模块,每个模块拥有独立的State,Getter,Mutation,Action,模块之中还可以嵌套模块

示例:store/index.js
export default new Vuex.Store({   //创建仓库
    state: {
        count: 0,
        total: 15,
    },
    getters: {
        tenTimesCount(state) {
            return state.count * 10;
        }
    },
    mutations: {
        addCount(state, num) {
            state.count += num || 1;
        }
    },
    actions: {
        // context具有和store实例相同的属性和方法
        // 可以通过context的state和getters中的值,或者提交mutation和分发其他的action
        addCountAsync(context, num) {
            setInterval(() => {
                if (context.state.count < 200) {
                    context.commit('addCount', num || 100);
                }
            }, num || 100);
        }
    },
    modules: {
        counter,
    }
})
其中注释的代码为另一种写法index.vue
import {mapState, mapGetters, mapMutations, mapActions} from 'vuex'

export default {
    name: 'Vuex',
    props: {},
    data() {
        return {}
    },
    computed: {
        ...mapState(['count', 'total']),
        ...mapState('counter', {
            counterCount: 'count'
        }),
        ...mapGetters(['tenTimesCount']),
        ...mapGetters('counter',{
            counterTenTimesCount: 'tenTimesCount'
        }),
        /*count() {
            return this.$store.state.count;
        }
        tenTimesCount() {
            return this.$store.getters.tenTimesCount
        }*/
    },
    methods: {
        ...mapMutations(['addCount']),
        ...mapMutations({ //为mutation赋别名,注意冲突
            increaseCount: 'addCount'
        }),
        ...mapMutations('counter',{ //为mutation赋别名,注意冲突
            increaseCounterCount: 'addCount'
        }),
        ...mapActions(['addCountAsync']),
        ...mapActions({ //为action赋别名,注意冲突
            increaseCountAsync: 'addCountAsync'
        }),
        ...mapActions('counter',{ //为action赋别名,注意冲突
            increaseCounterCountAsync: 'addCountAsync'
        }),
        /*addCount() {
            this.$store.commit('addCount', 10)
        },
        addCountAsync(num) {
            this.$store.dispatch('addCountAsync', num);
        },*/
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值