1、getters
state: { //存放变量的
counter:100,
},
getters:{ //类似计算属性,对数据进行再加工操作
powerCounter(state){ //默认会传state
return state.counter * state.counter
},
powerCounter2(state,xxx){ //这个xxx不管是什么变量名,都指的getters,所以传参用下面的方法
return state.counter * xxx.powerCounter()
},
addCount(state){ //如果要传参数进来。
return function (add2) {
return state.counter + add2
}
}
counterMore(state){//传入一个数
return function (num) {
return state.stu.filter( (stu)=>{
return stu.age > 20
})
}
}
}
使用:
<p>{{$store.state.counter}}</p>
<span>平方:{{$store.getters.powerCounter}}</span>
<div></div>
<span>加5的:{{$store.getters.addCount(5)}}</span>
2.mutations
mutations: { //必须使用该方法修改存放在state里面的变量
increment(state){
state.counter++
},
incrementCount(state,num){//这个地方要加参数直接在后面加
state += num
},
// vue-x的响应式,是要在Store里面初始化好对应的属性,
// 如果是添加新属性要调用set方法,Vue.set(obj,'变量名','value')
// 或者直接用新对象赋值给旧的对象。
updateInfo(state){
Vue.set(state.xxx,'','')
}
},
在mutations里面的方法名,组件中要用到commit可以把方法名定义成常量
比如新建mutations-type.js文件
export const INCREMENT = 'increment'
然后store/index.js
import {
INCREMENT
} from './mutations-type'
mutations: {
[INCREMENT](state){ //这个地方可以这么写方法名
state.counter++
},
}
在组件里面使用就可以
this.$store.commit(INCREMENT)
这样对产生了对应关系,
3.actions
当是异步耗时操作的时候,需要在
actions: {
aupdateInfo(context){ //这个方法是异步方法,所以要放在actions里面
setTimeout(()=>{
context.commit('updateInfo') //这个地方commit方法
},100)
}
},
mutations: {
updateInfo(state){
state.counter = 50
},
},
组件调用的时候:
changgeInfo(){
this.$store.dispatch('aupdateInfo')//这样就经过了actions
}
带参数的时候可以用函数实现
actions: {
aupdateInfo(context,payload){ //payload对象,带参数和回调
setTimeout(()=>{
context.commit('updateInfo')
console.log(payload.message)
payload.success()
},1000)
}
},
组件中:
changgeInfo(){
this.$store.dispatch('aupdateInfo',{
message:'abc',
success:()=>{
console.log('changgeInfo--end')
}
})
}
进阶版。
aupdateInfo(context,paload){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
context.commit('updateInfo')
console.log(paload.message)
resolve(paload)
},1000)
})
}
vue组件
changgeInfo(){
this.$store.dispatch('aupdateInfo',{
message:'abc',
}).then((paload)=>{
console.log('changgeInfo--end')
})
}
5.moudles模块化
对象的解构
vue-store文件的目录结构
可以把.store对象mutations、actions、getters、modules进行文件抽离,使结构更清晰
网友评论