const store=new Vuex.store(
state:{
counter:100,
students:[
{id:110,name:"why",age:18},
{id:111,name:"kobe",age:24},
{id:112,name:"james",age:30},
{id:113,name:"curry",age:10}
],
info:{name:"bill",age:40,height:180}
}
)
mutations:{
increment(state){
state.count++
}
}
increment:function(){
this.$store.commit(‘increment‘);
}
mutations:{
incrementCount(state,count){ //第1个参数固定为state
state.count+=count
}
}
//使用的时候
this.$store.commit(‘incrementCount‘,10);
updateInfo(state){
//state.info["address"]="洛城" //这样加不是响应式的,不会更新界面
Vue.set(state.info,‘address‘,‘洛城‘) //响应式的增加属性
// delete state.info.age //删除age属性,这样不是响应式的,不会更新界面
Vue.delete(state.info,‘age‘) //响应式的删除属性
}
export const INCREMENT_COUNT
mution定义,用常量定义这一个函数(官方推荐)
import * as types from ‘./mution-types‘
mutions:{
[types.INCREMENT_COUNT](state,count){
state.count+=count
}
}
提交时也用这一个常量
import {INCREMENT_COUNT} from ‘./store/mution-types‘
this.$store.commt(INCREMENT_COUNT,10)
actions:{
aUpdateInfo(context,payload){
setTimeout(()=>{
context.commit(‘updateInfo‘) //这里去提交mution,调用mution里的函数
console.log(payload) //我是传入的参数
},1000)
}
}
通过dispatch进行调用action
this.$store.dispatch(‘aUpdateInfo‘,‘我是传入的参数‘)
actions:{
aUpdateInfo(context,payload){
setTimeout(()=>{
context.commit(‘updateInfo‘) //这里去提交mution,调用mution里的函数
console.log(payload.message) //我是传入的参数
payload.success("成功了") //回调
},1000)
}
}
通过dispatch进行调用action
this.$store.dispatch(‘aUpdateInfo‘,{
message:‘我是传入的参数‘
success:(txt)=>{
console.log(txt) //成功了
}
})
2.通过Promise进行回调
actions:{
aUpdateInfo(context,payload){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
context.commit(‘updateInfo‘) //这里去提交mution,调用mution里的函数
console.log(payload) //我是传入的参数
resolve("成功了")
},1000)
})
}
}
this.$store.dispatch(‘aUpdateInfo‘,‘我是传入的参数‘)
.then((data)=>{
console.log(data) //成功了
})
getters:{
//count的平方
powerCounter(state){
return state.count*state.count
},
//年龄大于20的学生
more20stu(state){
return state.students.filter(s=>s.age>20)
},
//年龄大于20的人数
more20stuLength(state,getters){ //这里第2个参数是getters
return getters.more20stu.length
},
//年龄大于age的人数,age为传进来的一个参数
moreAgeStu(state){
return function(age){
return state.students.filter(s=>s.age>age)
}
},
//简写
moreAgeStu(state){
return age=>{
return state.students.filter(s=>s.age>age)
}
}
}
//使用
{{$store.getters.powerCounter}}
{{$store.getters.more20stu}}
{{$store.getters.more20stuLength}}
{{$store.getters.moreAgeStu(12)}}
const moduleA={
state:{},
mutations:{},
actions:{},
getters:{}
}
const moduleB={
state:{},
mutations:{},
actions:{},
getters:{}
}
const store=new Vuex.Store({
modules:{
a:moduleA,
b:moduleB
}
})
store.state.a //->moduleA的状态
store.state.b //->moduleB的状态
原文:https://www.cnblogs.com/bqh10086/p/13185404.html