vuex 是为了方便组件之间的数据交互,有5种属性:分别是state、mutation、getter、action、module
- 1、使用vuex的第一步,先去产生一个vuex实例
let store123 = new Vuex.Store({ xxx... }) - 2、把产生的实例注入到根实例中
let vm = new Vue({ el:'#app', store:store123,// 这个store属性名是vue规定的,不可以更改 data:{ name:"你好" }, components:{ //注册 bro1,bro2 } }); - 3、注册完成之后,发现每一个组件(实例)中都有$store这个属性了
vuex的5种属性:state、getter、mutation、action、module
state:存放共用数据
mutations:存放的是用来修改数据的方法
actions:存放的是用来调用mutations方法的函数,mutations中不能写异步
getters:计算属性
modules:分模块
let store123 = new Vuex.Store({
// 配置项
state:{ //通过$store.state.color可以在页面中使用
// 这里存放的都是公用数据
color:'red',
bro1Color:'blue',
bro2Color:'green'
},
mutations:{ //对象,通过this.$store.commit('mutations中的函数名',option参数)在组件中调用
// 这里的函数必须都是同步函数(它是认为约定不是技术规定),是为了方便状态可控,修改状态,有迹可循;
// 函数名自定义的
// 这里存放的都是用来修改上边state中的属性的方法
changeBro1Color(state,option){
// state就是vuex中的那个state; option 是调用这个函数时传递的参数;
// 这里的函数最多只有两个参数,第二个参数使用调用时传递的,若需要多个参数的时候
// 只能在调用的时候,把第二个参数转成引用数据类型包起来,传递进来
//console.log(arguments)
state.bro1Color = option;
},
changeBro2Color(state,option){
state.bro2Color = option
}
},
getters:{
// 理解成vuex的计算属性即可
// 什么时候才会选择使用getters:当多个组件共用一套处理逻辑的时候选择使用
// 若这个逻辑只在一个组件使用,不建议写getters中,因这个增大vuex的体积;
person(state){
return state.list.filter(item=>item.age>=18)
},
child(state){
return state.list.filter(item=>item.age<18)
}
},
actions:{
// 这里边也都是一些函数
// mutations中的函数,需要通过 commit触发
// actions中的函数,需要通过 dispatch触发
// actions中的函数,一般都会再去触发mutations中的方法
asyncAdd(store,option){
setTimeout(() => {
// 请求成功之后 再去触发mutations中的方法
store.commit('add',option)
}, 1000);
console.log(arguments)
}
},
modules:{
//模块划分
qqq:myqqq
}
})