最常用的核心概念包含:State、Getter、Mutation、Action
1、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"])
}
![]()
![]()
2、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
}
}
})
![]()
![]()
3、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].具体参数)
})
}
}