在vue3中使用vuex 4.x
首先你需要下载最新版本的vuex
npm install vuex@next -S
首先通过命令新建脚手架,在src目录下新建store文件夹。并创建index.js入口和modules文件夹(因为我把模块拆分了)
const user = {
namespaced: true,
state () {
return {
userCount: 0
}
},
mutations: {
addUserMutaition (state, payload) {
state.userCount += payload
},
increment (state, payload) {
state.userCount -= payload
}
},
actions: {
addAction ({ commit, dispatch }, payload) {
commit('addUserMutaition', payload)
},
increAction ({ commit }, payload) {
commit('increment', payload)
}
},
getters: {
addGetters (state, getters, rootGetters) {
return state.userCount * (getters.getters1)
},
getters1 (state, getters) {
return state.userCount + 100
}
},
modules: {}
}
export default user
在main.js这个入口文件中使用方法
import { createApp } from 'vue'
import App from './App.vue'
import store from './store'
// import router from './router'
const app = createApp(App)
// app.use(router)
app.use(store)
app.mount('#app')
在vue2组件中的用法, 和vue3组件中的用法
import { computed } from 'vue'
import { createNamespacedHelpers, useStore } from 'vuex'
const { mapState, mapGetters, mapActions, mapMutations } = createNamespacedHelpers('user')
第一种方式
在vue2 中使用vuex的方法和数据
computed: {
...mapState(['userCount']),
...mapGetters({
getters2: 'addGetters'
})
},
methods: {
...mapActions({
add2: 'addAction'
}),
...mapMutations({
addmutations: 'addUserMutaition'
})
},
第二种方式
在vue3中的使用, 当然代码的写法很多,
setup () {
const store = useStore()
const userState = computed(() => store.state.user.userCount)
const getterss = computed(() => store.getters['user/addGetters'])
const action1 = mapActions({
addCom: 'addAction',
decrtement: 'increAction'
})
const mutations = mapMutations({
addActiona: 'addUserMutaition',
decrementa: 'increment'
})
return {
userState,
getterss,
...action1,
...mutations
}
}
详细分解见一下代码地址:https://gitee.com/AabbCcDdEe_abcde/vuex_learn