Vue异步组件的三种实现方式
异步组件的特点:
Vue 只有在这个组件需要被渲染的时候才会从服务器端请求组件的相关js,且会把结果缓存起来供未来重渲染。
异步组件的好处:
提高性能。在大型应用中,我们可以将应用分割成小一些的代码块,并且只在需要的时候才从服务器加载一个模块。通常的使用就是在配置路由的时候,使用异步组件的加载方式,只有路由被触发时,才会加载对应的组件。而不是一次性加载所有的组件,这样很有利于提高性能。
异步组件三种实现方式
工厂函数
// 全局注册 Vue.component('child1', function (resolve) { require(['./components/child1'], resolve) }) // 局部注册 components: { Child1: function (resolve) { require(['./components/child1'], resolve) } }
promise
// 全局注册 Vue.component('child2', () => import('./components/child2')) // 局部注册 components: { Child2: () => import('./components/child2') }
高阶组件
高阶组件的方式可以处理异步组件的加载状态和错误状态。loading 和 error 支持传入组件。
// 全局注册 Vue.component('child3', () => ({ component: import('./components/child3.vue'), loading: {template: '<div>Loading</div>'}, error: {template: '<div>error</div>'}, delay: 200, timeout: 3000 }) ) // 局部注册 components: { Child3: () => ({ // 需要加载的组件 (应该是一个 `Promise` 对象) component: import('./components/child3.vue'), // 异步组件加载时使用的组件 loading: {template: '<div>Loading</div>'}, // 加载失败时使用的组件 error: {template: '<div>error</div>'}, // 展示加载时组件的延时时间。默认值是 200 (毫秒) delay: 200, // 如果提供了超时时间且组件加载也超时了, // 则使用加载失败时使用的组件。默认值是:`Infinity` timeout: 3000 }) }
浙公网安备 33010602011771号