Vue路由器总是在初始加载时加载延迟加载的模块

问题描述 投票:0回答:2

这是使用Vue官方路由器的延迟加载实现

SRC /路由器/ index.js

import Vue from "vue";
import VueRouter from "vue-router";

const Foo = () => import("@/components/Test2");

const Bar = () => import("@/components/Test");

Vue.use(VueRouter);

export default new VueRouter({
  mode: "history",
  routes: [
    {
      path: "/test",
      name: "test",
      component: Bar
    },
    {
      path: "/test2",
      name: "test2",
      component: Foo
    }
  ]
});

SRC / main.js

import Vue from "vue";
import App from "./App.vue";
import router from "./router";

Vue.config.productionTip = false;

new Vue({
  render: h => h(App),
  router
}).$mount("#app");

路由按预期工作但是延迟加载不能正常工作,当我在第一次加载时检查网络选项卡时我能够看到web包生成延迟加载的文件

javascript vuejs2 lazy-loading vue-router
2个回答
5
投票

问题是webpack preloadplugin为所有异步块添加了一个预取标记。要防止这种情况,请将以下内容添加到vue.config.js中

  chainWebpack: config => {
    config.plugins.delete('prefetch');
  }

资料来源:https://github.com/vuejs/vue-cli/issues/979#issuecomment-373027130


-1
投票

我相信你这样做有点不对..

如果您想启用块拆分然后延迟加载路径的组件,您的方法应该看起来像这样:

SRC /路由器/ index.js

import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter);

export default new VueRouter({
  mode: "history",
  routes: [
    {
      path: "/test",
      name: "test",
      component: () => import(/* webpackChunkName: "bar" */ '@/components/Test.vue')
    },
    {
      path: "/test2",
      name: "test2",
      component: () => import(/* webpackChunkName: "foo" */ '@/components/Test2.vue')
    }
  ]
});

这将创建名为'bar''foo'的单独块,这些块将仅在输入的路由上延迟加载。

© www.soinside.com 2019 - 2024. All rights reserved.