Vue 状态管理
1. Vuex
import { createStore } from 'vuex'
export default createStore({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
},
actions: {
async incrementAsync({ commit }) {
await someAsyncOperation()
commit('increment')
}
},
getters: {
doubleCount: state => state.count * 2
}
})
2. Pinia
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
getters: {
doubleCount: (state) => state.count * 2
},
actions: {
increment() {
this.count++
},
async incrementAsync() {
await someAsyncOperation()
this.increment()
}
}
})