这是使用Vue官方路由器的延迟加载实现
src / router / 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 Pack生成的延迟加载文件
答案 0 :(得分:3)
问题是webpack preloadplugin向所有异步块添加了预取标签。为了防止这种情况,请将以下内容添加到您的vue.config.js
chainWebpack: config => {
config.plugins.delete('prefetch');
}
来源: https://github.com/vuejs/vue-cli/issues/979#issuecomment-373027130
答案 1 :(得分:-1)
我相信您的做法有误。
如果要启用块拆分,然后延迟加载路由组件,则方法应如下所示:
src / router / 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'
的单独块,仅在输入的路由上才进行延迟加载。