vuex的state,getters,mutations,actions,modules

目录

Vuex核心概念:

State :存储应用状态数据的对象,与vue中data类似
Getters :类似vue的计算属性,store中数据的变化,getters的数据也会发生变化
Mutations :提交mutation来修改store中的状态,同步操作
Actions :与mutations类似,提交修改state的行为,处理异步任务(提交的是mutation,不是直接修改状态)
Modules :模块化状态管理,为了开发大型项目,方便状态管理而使用的

1、State

1)全局state

直接使用:

js 复制代码
 this.$store.state.xxx;

map辅助函数:

js 复制代码
computed: { 
  ...mapState(['xxx']), 
  ...mapState({'新名字': 'xxx'})
}

2)使用modules中的state

直接使用:

js 复制代码
this.$store.state.模块名.xxx;

map辅助函数:

js 复制代码
computed: { 
  ...mapState('模块名', ['xxx']), 
  ...mapState('模块名', {'新名字': 'xxx'})
}

2、Getters

1)全局Getters

直接使用:

js 复制代码
this.$store.getters.xxx;

map辅助函数:

js 复制代码
computed: { 
  ...mapGetters(['xxx']), 
  ...mapGetters({'新名字': 'xxx'})
}

2)使用modules中的getters

直接使用:

js 复制代码
this.$store.getters[模块名/xxx];

map辅助函数:

js 复制代码
computed: { 
  ...mapGetters('模块名', ['xxx']), 
  ...mapGetters('模块名',{'新名字': 'xxx'})
}

3、Mutations

1)全局Mutations

直接使用:

js 复制代码
this.$store.commit('mutation名', 参数);

map辅助函数:

js 复制代码
methods: { 
  ...mapMutations(['mutation名']), 
  ...mapMutations({'新名字': 'mutation名'})
}

2)使用modules中的mutations(namespaced:true)

直接使用:

js 复制代码
this.$store.commit('模块名/mutation名', 参数);

map辅助函数:

js 复制代码
methods: { 
  ...mapMutations('模块名', ['xxx']), 
  ...mapMutations('模块名',{'新名字': 'xxx'})
}

4、Actions

1)全局Actions

直接使用:

js 复制代码
this.$store.dispatch('action名', 参数);

map辅助函数:

js 复制代码
methods: { 
  ...mapActions(['actions名']), 
  ...mapActions({'新名字': 'actions名'})
}

2)使用modules中的actions(namespaced:true)

直接使用:

js 复制代码
this.$store.dispatch('模块名/action名', 参数)

map辅助函数:

js 复制代码
methods: { 
  ...mapActions('模块名', ['xxx']), 
  ...mapActions('模块名',{'新名字': 'xxx'})
}

5、有无modules的目录结构对比

没有使用modules的文件目录如下:

使用modules的文件目录如下:

相关推荐
pan_junbiao1 小时前
Go 语言基本数据类型
java·前端·golang
ZhengEnCi9 小时前
前端日志和后端日志怎么记:分级、JSON 格式、按天分文件与保留策略
前端·后端·python
kyriewen10 小时前
我给 61 个前端库排了两次名,最多差了 46 位
前端·javascript·程序员
程序员大阳10 小时前
副队长Vue3教程(33)--路由懒加载
vue.js·性能优化·vue3·路由·懒加载·速度慢
亲亲小宝宝鸭10 小时前
Cesium启动:TLE数据是如何变成轨迹线的
前端·cesium
阿里云云原生10 小时前
对话即构建,在 AgentCore 构建 Agent 就是这么简单
前端·agent
夕水11 小时前
我给我的诗写了个后台,顺手写了 一个组件库ew-solid-ui
前端·javascript·typescript
狗头大军之江苏分军12 小时前
前端转行干能干什么?我转行试了下(被迫)
前端·后端
孟陬12 小时前
Foobar 技术周刊#2:约会已死?用户急剧下滑,约会App大概率会弱化约会属性转向轻陪伴。我有个建议:
前端·后端·rust
parade岁月13 小时前
VTable Guild 3.0.0 发布,面向 Vue 3 的 ProTable 式业务表格
前端