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

相关推荐
hzxpaipai41 分钟前
杭州企业官网怎么建设?从策划到上线的5步建站方法
运维·服务器·前端·网络
怕浪猫1 小时前
2026年金九银十,我面了22个前端
前端·javascript·面试
IT_陈寒1 小时前
Vue 这个响应式陷阱,我的头发都掉没了
前端·人工智能·后端
FYKJ_20101 小时前
django电影推荐系统55066-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·typescript·spark·django
前端的日常1 小时前
一个人+AI做情侣食谱小程序,30天纯赚
前端·javascript·后端
qq_316837751 小时前
阿里云百炼 fun-asr-realtime uniapp vue3 调用
javascript·vue.js·uni-app
庄园特聘拆椅狂魔2 小时前
Java 后端转全栈的第一课:从前端项目搭建到技术选
java·开发语言·前端
triumph_passion2 小时前
前端路由策略:Memory、Hash 与 History
前端
李剑一2 小时前
AntDesign老版本没有月份和年份区间选择组件?我封装了一个完美版,附源码!
前端·vue.js
牧艺2 小时前
浏览器端 3D 看车重磅升级:从三款展车到可试驾的八车展厅
前端·three.js·交互设计