Vuex是干什么的?以及核心概念

本文深入解析Vuex,Vue.js的状态管理模式,涵盖State、Getter、Mutation、Action及Module等核心概念,阐述如何高效管理应用状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Vuex是干什么的?以及核心概念

  1. Vuex是专门为Vue.js设计的状态管理模式。它采用集中式储存管理Vue应用中所有组件的状态
  2. Vuex的核心概念:
    . State --> 数据源存放地 ,类似vue组件中的data,在组件中通过store.state可以访问
    . Getter --> 类似于vue组件中的计算属性,接受state作为第一个参数也接受其他的getter作为第二个参数,在组件中可以以访问state的方式访问store.getters,也可以使用mapGetters辅助函数 computed{ // 使用对象展开运算符将 getter 混入 computed 对象中 ...mapGetters([ 'doneTodosCount', ..... ]) }
    . Mutation --> 更改Vuex中State的唯一方法就是提交一个Mutation,非常类似于事件,每个mutation都有一个事件类型和一个回调函数,这个回调函数实际就是我们进行状态更改的地方,接受state作为第一个参数,注意mutation必须是同步函数mutations:{ increment (state,payload){ state.count += payload.amount } }
    触发时传入额外的参数:store.commit('increment ', { amount: 10 }) 或者 store.commit({ type: increment , amount: 10 })
    在组件中提交mutationsimport { mapMutations } from 'vuex'
    methods: { ... mapMutations ([ 'increment' // 将 this.increment()映射为 this.$store.commit('increment') ]) }
    . Action --> action类似于mutation,但是不同的是action提交的是mutation,而不是直接的去改变状态,action可以包含任意的异步操作,接受一个与store相同方法和属性的context对象
    actions: { incrementAsync({ commit }) { commit('increment') } } 或者 actions: { incrementAsync(context) { context.commit('increment') } }
    actions通过store.dispatch('incrementAsync')方法触发 ,或者传递额外参数 store.dispatch(‘incrementAsync’, payload) 或者 store.dispatch({ type: 'incrementAsync', amount: 10 })
    在组件中触发action: methods: { ...mapActions(['incrementAsync' // 将 this.incrementAsync() 映射为 this.$store.dispatch('incrementAsync')]) }
    . Module–> 由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
    为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值