外观
Vue状态管理核心(Vuex)
最常用的核心概念包含: State、Getter、Mutation、Action
Getter
对Vuex中的数据进行过滤
import { createStore } from 'vuex'
export default createStore({
state: {
counter: 0
},
getters: {
getCount(state){
return state.counter > 0 ? state.counter : "counter小于0,不符合要求"
}
}
})import { mapState,mapGetters } from 'vuex';
computed:{
...mapGetters(["getCount"])
}Mutation
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的事件类型 (type)和一个回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数
import { createStore } from 'vuex'
export default createStore({
state: {
counter: 0
},
getters: {
},
mutations: {
setCounter(state, num) {
state.counter += num
}
}
})import { mapState,mapMutations } from 'vuex';
methods:{
...mapMutations(["setCounter"]),
clickHandler(){
// this.$store.commit("setCounter",20)
// 或者
// this.setCounter(10)
}
}Action
Action 类似于 mutation,不同在于:
- Action 提交的是 mutation,而不是直接变更状态
- Action 可以包含任意异步操作
import { createStore } from 'vuex'
import axios from "axios"
export default createStore({
state: {
counter: 0
},
getters: {
getCount(state){
return state.counter > 0 ? state.counter : "counter小于0,不符合要求"
}
},
mutations: {
setCounter(state, num) {
state.counter += num
}
},
actions: {
asyncSetCount({ commit }){
axios.get("http://iwenwiki.com/api/generator/list.php")
.then(res =>{
commit("setCounter",res.data[0])
})
}
}
})import { mapState,mapMutations,mapGetters,mapActions } from 'vuex';
methods:{
...mapActions(["asyncSetCount"]),
clickAsyncHandler(){
// this.$store.dispatch("asyncSetCount")
// 或者
// this.asyncSetCount()
}
}