前言
在网站性能优化中,提高首屏加载速度,
几毫秒,可能就会带来几千,甚至几万的浏览量,
那么尽可能的少些内容,如首屏展示的内容,尽量不去加载,就可以提高首屏的加载速度。
如,我们要展示某个触发事件,效果组件,那么这个组件就不需要加载,可以异步组件方式。
异步组件,简单使用
1.异步组件,vue3使用方式
<template>
<Music></Music>
</template>
<script>
export default {
name: 'App',
data(){
return {
myMusic:"Music"
}
}
components: {
Music:defineAsyncComponent(() => import('./components/App/Music.vue'))
},
}
</script>
2.异步组件,vue2使用方式
<template>
<Music></Music>
</template>
<script>
export default {
name: 'App',
data(){
return {
myMusic:"Music"
}
}
components: {
Music:()=>import("./components/App/Music.vue")
},
}
</script>
异步组件,高级使用
1.异步组件,vue2使用方式
<script>
import LoadingComponent from '@/components/HelloWorld.vue'//组件加载成功
import ErrorComponent from '@/components/ErrorComponent'//组件加载失败
//官方文档2.3.0+新增
const HelloWorld = () => ({
// 需要加载的组件 (应该是一个 `Promise` 对象)
component: import('./MyComponent.vue'),
// 异步组件加载时使用的组件
loading: LoadingComponent,
// 加载失败时使用的组件(超时)
error: ErrorComponent,
// 展示加载时组件的延时时间。默认值是 200 (毫秒)
delay: 200,
// 如果提供了超时时间且组件加载也超时了,
// 则使用加载失败时使用的组件。默认值是:`Infinity`
timeout: 3000
})
</script>
2.异步组件,vue3使用方式
<script>
import LoadingComponent from '@/components/HelloWorld.vue'//组件加载成功
import ErrorComponent from '@/components/ErrorComponent'//组件加载失败
const HelloWorld = defineAsyncComponent({
// 需要加载的组件 (应该是一个 `Promise` 对象)
// 之前是 component,现在改叫 loader 了
loader: import('./MyComponent.vue'),
// 异步组件加载时使用的组件
loading: LoadingComponent,
// 加载失败时使用的组件(超时)
error: ErrorComponent,
// 展示加载时组件的延时时间。默认值是 200 (毫秒)
delay: 200,
// 如果提供了超时时间且组件加载也超时了,
// 则使用加载失败时使用的组件。默认值是:`Infinity`
timeout: 3000
})
</script>