一、Vuex
1、定义
vuex是vue的全局状态的管理工具
vuex数据更新,其引用的组件都会响应式的更新
2、模块
1. state 存放数据的地方,组件中 $store.state.xxx
2. getters 从现有数据计算出新的数据,组件中 $store.getters.xxx
3. mutations 改变state(唯一方式),组件中 $store.commit(方法,数据)
4. actions 异步方法,组件中 $store.dispatch(方法,数据)
5.modules
export default new Vuex.Store({
// state存储数据的地方
state: {
cartNum:10,
price:255,
},
// 从现有数据计算出新的数据
getters: {
// 从现有的价格计算出fee
fee:function(state){
return state.price*0.5;// 价格的50%
}
},
// mutations是改变数据state的唯一方式
mutations: {
// 更改购物车的数量
SET_CARTNUM(state,data){
state.cartNum=data;
}
},
// actions动作,异步,延迟方法,不能直接修改state
actions: {
setCart(context,data){
setTimeout(()=>{
// context就是$store
// 等待4秒把执行SET_CARTNUM,传参参数data
context.commit("SET_CARTNUM",data)
},4000)
}
},
modules: {
user,// 注册模块
cart,// test,
}
})
// state状态 getters获取器 mutations改变,变异 actions动作 modules子模块
// vue就是vuex全局数据与方法存储的地方,使用跨组传参
actions和mutations区别
1.mutations改变state数据的唯一方式
2.actions异步,ajax操作
3.如果一个方法多次被使用,且需要异步请求,可以定义在actions
二、映射
1、mapState
把vuex的state在computed映射为组件的data
...mapState({
score:state=>state.test.score
})
//test是模块名,score数据名
2、mapGetters
没有命名空间
...mapGetters({fee:"fee"}),
...mapGetters(["fee"]),
有命名空间
...mapGetters({rank:"test/rank"}),
3、mapActions
没有命名空间
...mapActions({login:"login"}),
...mapGetters(["login"]),
有命名空间
...mapActions({login:"test/login"}),
4、mapMutations
没有命名空间
...mapMutations({setUser:"SET_USERINFO"}),
有命名空间
...mapMutations:{setScore:"test/SET_SCORE"},
三、模块的命名空间
作用:避免命名冲突 namespaced:true
state的访问默认是有命名空间的,getters,actions,mutations需要开启后才有命名空间