vuex
State:定义了应用状态的数据结构,可以在这里设置默认的初始状态。 类似于data
Getter:允许组件从 Store 中获取数据,mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性。 类似于computed
Mutation:是唯一更改 store 中状态的方法,且必须是同步函数。 类似于methods
Action:用于提交 mutation,而不是直接变更状态,可以包含任意异步操作。 异步是dispatch
Module:可以将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割
1. State
const store=new Vuex.Store({
state:{
count:5
}
})
2. getters
const store =new Vuex.Store({
state:{
count:5
},
getters:{
newCount:state=> state.count*5 //箭头函数 不加花括号直接return
}
})
在组件中获取方式----newCount
export default {
computed:{
newCount(){
return this.$store.getters.newCount
}
}
}
3. Mutation
我们在 mutations中定义了一个叫increment的函数,函数体就是我们要进行更改的地方
会接受 state作为第一个参数,第二个是自定义传参
const store=new Vuex.Store({
state:{
count:5
},
mutations:{
increment(state,value){
state.count += value;
}
}
})
我们在提交commit时候,字符串参数increment,就是对应在 mutations中的increment
export default ({
methods:{
get(){
this.$store.commit('increment',3)
}
}
})
4.Action
用于提交 mutation,而不是直接变更状态,可以包含任意异步操作。
只有通过action=>mutations=>states,这个流程进行操作,具体步骤如下:
const store=new Vuex.Store({
state:{
count:5
},
mutations:{
increment(state,value){
state.count += value;
},
},
action:{
//第一个参数为store,可以任意起名,若{commit},变量解构-- commit=store.commit
getAsync(store){
//action 函数接收一个 store 的实例对象,因此你可以调用 store.commit 提交mutation
store.commit('increment',10)
}
}
})
//组件里使用
methods:{
getAsync(){
this.$store.dispacth('getAsync')
}
//还可以使用数组解构 methods的函数名和mutation函数名一样
...mapActions(['getAsync'])
}