vue3+vuex4,如获取模块state中的值,如何获取模块getters中的值,如何提交mutation和触发action
store 写法
模块a.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| export default { namespaced: true, state: () => ({ configs: { list: [] }, }), getters: { list (state) { return state.configs.list || [] }, }, actions: { async myAction ({ commit }) { const url = 'http://.....' const res = await ajax.get(url) const { status, data } = res if (status === 200 && data) { commit('myMutation', data) } },
}, mutations: { myMutation (state, payload) { state.configs = payload }, }, }
|
modules.js
1 2 3 4 5 6 7 8
| import a from './a.js' ...其他模块...
export default { a, ...其他模块... }
|
store.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| import { createStore } from 'vuex' import modules from './modules'
const store = createStore({ modules,
state: {},
mutations: { },
actions: { },
getters: { } })
export default store
|
在.vue文件中 使用 store
.vue文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| <script setup>
import { computed } from 'vue' import { useStore } from 'vuex'
const store = useStore() const list = computed(() => store.getters['a/list']) const config = computed(() => store.state.a.config)
const changeSite = (index) => { store.commit('a/myMutation', [index]) store.dispatch('a/myAction') } </script> <template> <template v-for="(item, index) in list" :key="index" > <div>{ {item} }</div> </template>
|