在大型项目中,我们可能需要拆分应用为更小的块,并仅在需要时再从服务器加载相关组件。Vue 提供了 defineAsyncComponent
方法来实现此功能:
1 <template> 2 <h3>异步加载</h3> 3 <KeepAlive> 4 <component :is="tabComponent"></component> 5 </KeepAlive> 6 <button @click="changeHandle">切换组件</button> 7 </template> 8 9 <script> 10 11 import { defineAsyncComponent } from "vue" 12 import ComponentA from "./components/ComponentA.vue" 13 const AsyncComponentB =defineAsyncComponent (()=> 14 import('./components/ComponentB.vue') 15 ) 16 17 export default{ 18 data(){ 19 return{ 20 tabComponent:"ComponentA" 21 } 22 }, 23 methods:{ 24 changeHandle(){ 25 this.tabComponent=this.tabComponent=="ComponentA"?"AsyncComponentB":"ComponentA" 26 } 27 }, 28 components:{ 29 ComponentA, 30 AsyncComponentB 31 } 32 33 } 34 </script>
切换组件时,网络请求会加载B
标签:异步,tabComponent,vue,ComponentA,18,defineAsyncComponent,vue3,AsyncComponentB,加载 From: https://www.cnblogs.com/wuzexin/p/17545486.html