如何只加载我使用 Vue.js 和 Vue-router 调用的路由

How to load just routs that I call using Vue.js and Vue-router

我正在使用 Vue.js 开发应用程序 SPA,我意识到当我使用 Vue-router 调用导入来加载路由时,它正在加载所有内容。

我当前的代码:

import Home from './components/Home/Home.vue';
import Product from './components/Product/Index.vue';
import Participant from './components/Participant/Index.vue';

export const routes = [
    {
        path: '', 
        component: Home, 
        name: 'home',
        comments: {
            default: Home
        }
    },
    {
        path: '/product', component: Product
    },
    {
        path: '/participant', component: Participant
    },
    {   path: '*', redirect: '/' }
];

我想知道是否有任何东西可以只加载部分屏幕以成为真正的 SPA,我的意思是当它收到对菜单的点击时。

我的菜单代码:

<router-link class="nav-item" tag="li" to="/"><a class="nav-link">Home</a></router-link>
<router-link class="nav-item" tag="li" to="/product"><a class="nav-link">Product</a></router-link>
<router-link class="nav-item" tag="li" to="/participant"><a class="nav-link">Participant</a></router-link>

我已经在一个 Vue.js 项目中实现了一些东西,我相信这正是您希望在您的应用程序中使用的东西。

您需要使用 resolve 方法将 imports 更改为 const,但是,主页应该保持原样,因为它是默认页面

您可以试试下面的代码:

import Home from './components/Home/Home.vue';

const Product = resolve => {
    require.ensure(['./components/Product/Index.vue'], () => {
        resolve(require('./components/Product/Index.vue'));
    });
};

const Participant = resolve => {
    require.ensure(['./components/Participant/Index.vue'], () => {
        resolve(require('./components/Participant/Index.vue'));
    });
};

它允许使用延迟加载概念,它只会在调用时加载。