记一次在nuxt中按需加载vuex中的store

随着项目内容的越来越丰富,不可避免地会出现vuex中的状态越来越庞大,其实我们可以借鉴按需加载的方式去优化它。

在nuxt中提供了store.registerModule的api,下面我记录一下我的优化过程:

1、在nuxt的nuxt.config.js中的plugins 加入storeCreate

{ src: "@/plugins/storeCreate.js", ssr: true },

2、在根目录的plugins下新建storeCreate.js文件,内容如下:

// ---------
//动态注入相关球类的store
// ---------

export default async ({ route, store }) => {
  let f_name = [];
  let path = route?.fullPath || '';
  let mod = store.state.proModule;
  // console.log(path, mod);
  if (mod == "football") {
    if ((route && route.name?.includes("home-list")) || path.includes('/football/')) {
      f_name = ["football/home"];
    } else if (path.includes("/match-")) {
      f_name = ["football/detail"];
    } else if (path.includes("/tournament-")) {
      f_name = ["football/comp", "football/home"];
    } else if (path.includes("/team-")) {
      f_name = ["football/team", "football/home"];
    } else if (path.includes("/player-")) {
      f_name = ["football/player", "football/home"];
    }else {
      f_name = ["football/home", "football/detail", 'football/comp', 'football/team', 'football/player'];
    }
  } else {
    f_name = [mod];
  }
  // console.log('f_name', f_name)
  for (let i = 0; i < f_name.length; i++) {
    if (!store.hasModule(f_name[i])) {
      let res = await import(/* webpackChunkName: "mystore-[request]" */ `../mystore/${f_name[i]}/index.js`);
      store.registerModule(f_name[i], res.default, {
        preserveState: process.client,
      });
    }
  }
};

代码可能丑陋了点,但是理不糙哈~

store.hasModule : 判断是否已经注册过了,

store.registerModule :注册store,

preserveState: process.client  在客户端的时候保留store内容,

默认情况下如果在根目录的store下面去新建的store相关的js,nuxt会加载全部

 所以我们就需要自己在根目录新建一个myStore了,以football/home为例:

 记得加上namespaced:true 

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值