隐藏应用程序中的其他代码.js在 vue 应用程序的登录页面中



我正在使用laravel + vue创建一个应用程序。Vue 在应用程序中加载所有 javascript 代码.js甚至在用户尚未进行身份验证的登录页面中也是如此。在用户登录之前,我还不想公开所有 js 代码。有什么方法可以只显示登录页面的必要代码而不公开应用程序的所有js代码吗?我这样做也是为了限制应用程序的大小.js下载用于登录页面以改善页面加载时间。

如果您使用的是 Laravel mix,则可以为登录脚本添加新的入口点。

mix.js('resources/assets/app/js/app.js', 'public/app/js')
.js('resources/assets/app/js/login.js, 'public/app/js);

因此,您可以在基本布局中添加 @yield 语句,以放置页面视图中声明的脚本。

base.blade.php

<html>
<head>
<title>App Name - @yield('title')</title>
</head>
<body>
@section('sidebar')
This is the master sidebar.
@show
<div class="container">
@yield('content')
</div>
@yield('scripts')
</body>
</html>

login.blade.php

@extends('layouts.base')
@section('title', 'Page Title')
@section('content')
<p>This is my body content.</p>
@stop
@section('scripts')
<script src="{{ mix('app/js/login.js') }}"></script>
@stop

编辑

对于 SPA,您可以使用另一个捆绑的入口点来定义登录组件:


Vue.component('login-form', {
... component code here
})

你可以使用 vue-plugin-load-script 从 Vue 路由器加载beforeEach方法中的login.js脚本。因此,该组件将在呈现登录页面之前可用。

router.beforeEach(async (to, from, next) => {
if (to === 'login'){
await Vue.loadScript('login entry point url here')
}
next();
});

此外,您可以使用beforeMount钩在页面内执行此操作。这里有一个使用虚假承诺和切入点的例子。

https://jsfiddle.net/7oj2sxun/3/

如果你使用的是 Vue CLI,它已经支持动态导入的延迟加载。

这里有一篇详细的文章:

https://blog.logrocket.com/lazy-loading-in-vue-js/

最新更新