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的文件目录如下:

相关推荐
!执行20 分钟前
Web3 前端与合约交互
前端·web3·1024程序员节
潘小安24 分钟前
跟着 AI 学(二)- Quill 接入速通
前端
十里-36 分钟前
在 Vue2 中为 Element-UI 的 el-dialog 添加拖拽功能
前端·vue.js·ui
shada41 分钟前
从Google Chrome商店下载CRX文件
前端·chrome
左耳咚1 小时前
项目开发中从补码到精度丢失的陷阱
前端·javascript·面试
D_C_tyu1 小时前
Vue3 + Element Plus 实现前端手动分页
javascript·vue.js·elementui
黑云压城After1 小时前
vue2实现图片自定义裁剪功能(uniapp)
java·前端·javascript
芙蓉王真的好11 小时前
NestJS API 提示信息规范:让日志与前端提示保持一致的方法
前端·状态模式
dwedwswd1 小时前
技术速递|从 0 到 1:用 Playwright MCP 搭配 GitHub Copilot 搭建 Web 应用调试环境
前端·github·copilot
千里码aicood1 小时前
python+vue旅游购票管理系统设计(源码+文档+调试+基础修改+答疑)
vue.js·python·旅游