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

相关推荐
开开心心就好2 分钟前
视频里的图片怎么提取?双击一下就导出
java·前端·人工智能·spring·智能手机·intellij-idea·excel
爱喝水的小周5 分钟前
实验十 Vue‑Router 王者荣耀战绩查询 APP 开发实践
前端·javascript·vue.js
yexianglunbai6 分钟前
Vue 3 全面详解:从核心特性到工程化实践
前端·javascript·vue.js
传人once7 分钟前
选择文件按钮样式如何美化
前端·html·css3·jquery·html5
parade岁月23 分钟前
告别 Deno 时代?运行时进入一年倒计时,Deno 团队并入 Cloudflare
前端
Lucky_Turtle27 分钟前
【HTML】前端页面禁止缩放
前端·html
恋猫de小郭32 分钟前
Genkit Dart 1.0 发布,Flutter 原生的 AI Agent 终于完整了
android·前端·flutter
专业程序开发源36 分钟前
django便利店外卖后台管理系统19650-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·python·django·课程设计
思码梁田39 分钟前
CSS transform 转换详解:translate、rotate、scale、skew 与 3D 变换一次讲清
前端·css·transform·skew·scale·translate·rotate
第10086个小白1 小时前
flutter桌面端打包方式(Inno Setup Compiler)版本
前端·flutter