VueX - 在说Vue3之前,先回忆一下VueX:
- Vuex是vue的状态管理工具,为了更方便的实现多个组件共享状态
- 单项数据流理念
核心概念
一. state & 辅助函数mapState
- state 注册变量 ,
this.$store.state.xxx取值 - mapState
import {mapState} from VuexmapState(['XXX','XXX'])此返回的是一个计算属性对象,对象内有一个个函数。- 所以在vue组件中就可以这样使用:
computed:{...mapState['aaa','XXX']},然后直接使用aaa变量就行- 改名小技巧:
computed:{...mapState[{storeCount:state=>state.xxx}]}, 同理后面直接使用storeCount变量就行 - 改名简写:
computed:{...mapState[{storeCount:'xxx'}]}, xxx就等同于上方那个函数的返回
二. getter & 辅助函数mapGetters
- getters 注册函数 ,
this.$getters.XXX取值,可返回值, 也可返回函数通过this.$getters.XXX(2)取值 - 相当于store的计算属性,getter的返回值会根据它的依赖缓存起来,且只有当他的依赖值发生改变时才会被重新计算
- getter接收state作为第一个参数,getters作为其第二个参数
- 返回值
new Vuex.Store({state:{count:2},getters:{double(state){return state*2}}}) - 返回函数
new Vuex.Store({state:{count:2},getters:{add(state){return function(num)=>{return state.count + num}}}}) - mapGetters && mapMutations
import {mapGetters} from VuexmapGetters(['XXX','XXX'])此返回的同样是一个计算属性对象,对象内有一个个函数- 同mapState,
computed:{...mapGetters['aaa','XXX']},然后直接使用aaa函数就行三. mutations : 想改边state里面的值就要通过此 - mutations注册函数, this.$store.commit('XXX','可以传一个参数')取值
mutations:{change(state,'接收外面传来的参数'){state.stuList.push({name:'哈气'})}},然后直接使用change函数就行- mapMutations
import {mapMutations} from VuexmapMutations(['XXX','XXX'])此返回的同样是一个对象,对象内有一个个函数methods:{...mapMutations['aaa','XXX']},然后直接使用aaa函数就行- 当然这个也能改名字 四. actions && mapActions 类似mapMutations
- mutations只能执行同步,所以actions就起到作用了,就不过多赘述了
- actions注册函数, this.$store.dispatch('XXX','可以传一个参数')取值 ,传参同mutations
actions:{change({commit}){commit('mutations里的函数名'),'接收参数'},然后直接使用change函数就行- mapActions
import {mapActions} from VuexmapActions(['XXX','XXX'])此返回的同样是一个对象,对象内有一个个函数- 同mapActions,
methods:{...mapActions['aaa','XXX']},然后直接使用aaa({'传到actation中的参数'})函数就行
modules
-
在vuex中有一个modules对象概念。key值是模块的名字,value是模块的配置
-
例子:
new Vuex.Store({modules:{stu1:{state:{},getters:{},mutations:{},actions:{}}}}) -
注:当开启moudles后state会放在模块下,其余getters,mutations和actions都会放在全局下 -所以当想获取模块中的state时,
this.$store.state.stu1.xxx -
其余获取操作不变
-
this.$store.getters.xxx -
this.$store.commit(xxx,'传过去的参') -
this.$store.dispatch(xxx,'传过去的参') -
通过mapXxx的方式获取模块中的值
-
同样不能用之前的方式,获取state中的值
-
先引入
import{mapState,mapGetters,mapMutations,mapActions} -
例如正常获取ggetters
computed:{...mapGetters(['xxx'])} -
注使用map的方式可以获取getters,mutations,actions , 但是不能获取state
-
要想获取state,就要在模块的名字下开启命名空间
-
modules:{stu1:{namespaced:true,state:{},...}} -
但是开启命名空间后getters,mutations,actions都不能用之前方式获取了, 因为getters中的函数名字都变成了 stu1/xxx 这种。其余的也类似
开启命名空间后四个参数的获取方式
- 先引入
import{mapState,mapGetters,mapMutations,mapActions} computed:{...mapState('stu1',['xxx'])}- 或
this.$store.state.stu1.xxx computed:{...mapGetters('stu1',['xxx'])}- 或
this.$store.getters['stu1/xxx'] methods:{this.$store.commit('stu1/xxx','传的值')}this.$store.dispatch('stu1/xxx','传的值')- 使用mapxxx总结, 其实都类似
mapxxx('stu1',['xxx'])mapxxx('stu1',{'新名字':'注册的名字'})上方有个小技巧详细介绍