store/modules/home.js export default { state: { // 服务器数据 banners: [], recommends: [] }, mutations: { changeBanners(state, banners) { state.banners = banners }, changeRecommends(state, recommends) { state.recommends = recommends } }, actions: { fetchHomeMultidataAction(context) { return new Promise(async (resolve, reject) => { // 3.await/async const res = await fetch("http://123.207.32.32:8000/home/multidata") const data = await res.json() // 修改state数据 context.commit("changeBanners", data.data.banner.list) context.commit("changeRecommends", data.data.recommend.list) resolve("aaaaa") }) } } }
store/index.js import { createStore } from 'vuex' import homeModule from './modules/home' const store = createStore({ state: () => ({ }), getters: { }, mutations: { }, actions: { }, modules: { home: homeModule, } }) export default store
使用 : <template> <div class="home"> <h2>Home Page</h2> <ul> <!-- 获取数据: 需要从模块中获取 state.modulename.xxx --> <template v-for="item in $store.state.home.banners" :key="item.acm"> <li>{{ item.title }}</li> </template> <!-- 2.使用getters时, 是直接getters.xxx --> </ul> </div> </template> <script> </script> <script setup> import { useStore } from 'vuex' // 告诉Vuex发起网络请求 // 派发事件时, 默认也是不需要跟模块名称 // 提交mutation时, 默认也是不需要跟模块名称 const store = useStore() store.dispatch("fetchHomeMultidataAction").then(res => { console.log("home中的then被回调:", res) }) </script> <style scoped> </style>
标签:const,modules,state,vue2,vue3,home,data,store From: https://www.cnblogs.com/qd-lbxx/p/16639144.html