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

相关推荐
RainbowSea24 分钟前
NVM 切换 Node 版本工具的超详细安装说明
java·前端
读书点滴29 分钟前
笨方法学python -练习14
java·前端·python
Mintopia36 分钟前
四叉树:二维空间的 “智能分区管理员”
前端·javascript·计算机图形学
Mintopia1 小时前
Three.js 深度冲突:当像素在 Z 轴上玩起 "挤地铁" 游戏
前端·javascript·three.js
Penk是个码农1 小时前
web前端面试-- MVC、MVP、MVVM 架构模式对比
前端·面试·mvc
markyankee1011 小时前
Vue.js 入门指南:从零开始构建你的第一个应用
vue.js
MrSkye1 小时前
🔥JavaScript 入门必知:代码如何运行、变量提升与 let/const🔥
前端·javascript·面试
白瓷梅子汤1 小时前
跟着官方示例学习 @tanStack-form --- Linked Fields
前端·react.js
爱学习的茄子1 小时前
深入理解JavaScript闭包:从入门到精通的实战指南
前端·javascript·面试
zhanshuo2 小时前
不依赖框架,如何用 JS 实现一个完整的前端路由系统
前端·javascript·html