The content of this article is about how to use Webpack's code separation to implement Vue loading. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
When a Vue project becomes very large, use the code separation function of Webpack to Vue Components
, routes
or Vuex
code is separated and loaded on demand, which will greatly improve the loading speed of the first screen of the App.
In Vue projects, we can use lazy loading and code separation functions in three different situations:
Vue components, also known as asynchronous components
Vue-Router
Vuex
What the three have in common is the use of dynamic import , which was supported in the second version of Webpack.
Lazy loading in Vue components
In Eggheads, there is an explanation about using Vue asynchronous components to load components on demand.
To implement asynchronous components, you only need to use the import
function to register the component:
Vue.component('AsyncCmp', () => import('./AsyncCmp'))
You can also use the local registration method:
new Vue({ // ... components: { 'AsyncCmp': () => import('./AsyncCmp') } })
Use The arrow function points to the import
function, and Vue
will execute the code that requests to load the component when the component is needed.
If the imported component is exported using a named method, you can use object destructuring in the return value of Promise
to load the component on demand. The following is an example of loading KeenUI's UiAlert component:
components: { UiAlert: () => import('keen-ui').then(({ UiAlert }) => UiAlert) }
Lazy loading in Vue router
Vue router natively supports lazy loading. In the same way as lazy loading of components, the import
function is used. For example, we want to lazily load the Login
component under the /login
route.
// 不再使用 import Login from './login' const Login = () => import('./login') new VueRouter({ routes: [ { path: '/login', component: Login } ] })
Lazy loading in Vuex
Vuex’s registerModule
method allows us to dynamically create Vuex modules. If we use the import
function to return the module as the payload in Promise
, lazy loading is achieved.
const store = new Vuex.Store() ... // 假设我们想加载'login'这个模块 import('./store/login').then(loginModule => { store.registerModule('login', loginModule) })
Summary
Lazy loading is very simple in Vue Webpack. Quickly use the methods learned above to separate the code of your Vue project and load them on demand when they are needed. This can significantly reduce the time of loading the first screen of the application.
Related recommendations:
System summarizes commonly used JS methods to organize (collect)
Webpack4 and react implementation methods for building multi-page applications
The above is the detailed content of How to use Webpack's code separation to implement Vue loading. For more information, please follow other related articles on the PHP Chinese website!