首先呢,这是一个vue的文件,里面加载了一个HelloWorld组件
<template>
<div class="home">
<h1>Vue中异步组件的使用</h1>
<button @click='show = !show'>按钮</button>
<div v-if='show'>
<HelloWorld msg='这是一个异步的组件'></HelloWorld>
</div>
</div>
</template>
<script>
import HelloWorld from '@/components/HelloWorld.vue'
export default {
name: 'HomeView',
components: {
HelloWorld
},
data: ()=>({
show: false
}),
}
</script>
<template>
<div class="hello">
<h1>{{ msg }}</h1>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: String
}
}
</script>
我们再浏览器中刷新可以看到,加载了三个文件
我们把异步组件加载出来也并不没有什么东西加载进来
使用异步组件
修改我们的代码
vue3 中为我们提供了 defineAsyncComponent 方法
<template>
<div class="home">
<h1>Vue中异步组件的使用</h1>
<button @click='show = !show'>按钮</button>
<div v-if='show'>
<HelloWorld msg='这是一个异步的组件'></HelloWorld>
</div>
</div>
</template>
<script >
// import HelloWorld from '@/components/HelloWorld.vue'
import { defineAsyncComponent } from 'vue'
const HelloWorld = defineAsyncComponent(()=> import('@/components/HelloWorld.vue'))
export default {
name: 'HomeView',
components: {
HelloWorld
// HelloWorld: import('@/components/HelloWorld.vue') // vue2 的写法
},
data: ()=>({
show: false
}),
}
</script>
我们再浏览器中刷新可以看到,加载了三个文件
但是你也可以看到 我们的 app.js 文件变小了
我们把异步组件加载出来的时候,发现多加载了一次js
再完善一下异步组件
修改我们 的测试文件
如果我们要加载的异步组件比较大,那么会先加载Loading
组件,等HelloWorld
完全加载时再展示
<template>
<div class="home">
<h1>Vue中异步组件的使用</h1>
<button @click='show = !show'>按钮</button>
<div v-if='show'>
<AsyncHelloWorld msg='这是一个异步的组件'></AsyncHelloWorld>
</div>
</div>
</template>
<script >
import { defineAsyncComponent } from 'vue'
import Loading from './Loading'
import ErrorC from './Error'
// 这个webpackChunkName可以再浏览器中看到
const AsyncHelloWorld = defineAsyncComponent({
loader: ()=> import(/*webpackChunkName: 'HelloWorld'*/ '@/components/HelloWorld.vue'),
loadingComponent: Loading,
errorComponent: ErrorC,
delay: 200,
timeout: 3000,
suspensible: true // 定义组件是否可以挂起
})
// VUE2 的方式
// const asyncPageWithOptions = {
// component: () => import(/*webpackChunkName: 'HelloWorld'*/ '@/components/HelloWorld.vue'),
// delay: 200,
// timeout: 3000,
// error: ErrorComponent,
// loading: LoadingComponent
// }
export default {
name: 'HomeView',
components: {
AsyncHelloWorld
},
data: ()=>({
show: false
}),
}
</script>
<template>
<div class="loading">
<h1>loading</h1>
</div>
</template>
<template>
<div class="Error">
<h1>Error</h1>
</div>
</template>
再浏览器中我们可以看到,我们设置的 loading组件跟 chunkName 都生效了
最后再展示我们的异步组件