1.创建目录文件

首先通过命令新建脚手架,在src目录下新建store文件夹。并创建index.js入口和modules文件夹(因为我把模块拆分了)
image.png

2.store/index.js文件

  1. import { createStore, createLogger } from 'vuex'
  2. import home from './modules/home'
  3. import dome2 from './modules/dome2'
  4. const debug = process.env.NODE_ENV !== 'production'
  5. export default createStore({
  6. modules: {
  7. home,
  8. dome2
  9. },
  10. strict: debug,
  11. plugins: debug ? [createLogger()] : []
  12. })

3.home.js文件,一个独立的模块

  1. import {getErshoufang} from '../../api/home';
  2. const state = () => ({
  3. ershoufang:{},
  4. ResblockInfo:{},
  5. rent:{},
  6. overseas:{}
  7. })
  8. // getters
  9. const getters = {
  10. }
  11. // mutations
  12. const mutations = {
  13. setErshoufang (state,payload) {
  14. state.ershoufang = payload;
  15. },
  16. }
  17. // actions
  18. const actions = {
  19. async getErshou({ commit, state }){
  20. try{
  21. let {data} = await getErshoufang();
  22. commit('setErshoufang',data);
  23. }catch(e){
  24. console.log(e);
  25. }
  26. }
  27. }
  28. export default {
  29. namespaced: true,
  30. state,
  31. getters,
  32. actions,
  33. mutations
  34. }

4.使用store

  1. <script>
  2. import {mapState,mapActions} from 'vuex'
  3. export default {
  4. computed: {
  5. ...mapState(['ershoufang']),
  6. },
  7. methods: {
  8. ...mapActions({
  9. getErshou:"home/getErshou"
  10. }),
  11. },
  12. created () {
  13. this.getErshou();
  14. }
  15. }
  16. </script>

5.在setup中使用store

  1. <script setup>
  2. import { onMounted, toRaw } from "vue";
  3. import { useStore } from "vuex";
  4. //使用vuex
  5. const store = useStore();
  6. store.dispatch("home/getErshou");
  7. store.dispatch("home/getResblock");
  8. store.dispatch("home/getRents");
  9. store.dispatch("home/getoverseases");
  10. onMounted(() => {
  11. let rent = toRaw(store.state.home);
  12. console.log(rent);
  13. });
  14. </script>