全部学科
Python全栈
python
NodeJS全栈
nodejs
📅 2026-05-20 6 分钟 ✍️ juanwangdev

动态组件与异步组件

动态组件

使用 <component> 标签和 :is 属性动态切换组件:

vue
<template>
  <component :is="currentTab"></component>
  <button @click="currentTab = 'Home'">首页</button>
  <button @click="currentTab = 'Posts'">文章</button>
</template>

<script>
import Home from './Home.vue'
import Posts from './Posts.vue'

export default {
  components: { Home, Posts },
  data() {
    return { currentTab: 'Home' }
  }
}
</script>

keep-alive 缓存

vue
<keep-alive>
  <component :is="currentTab"></component>
</keep-alive>

使用 <keep-alive> 保持组件状态,避免重新渲染。

异步组件

JavaScript
import { defineAsyncComponent } from 'vue'

const AsyncComp = defineAsyncComponent(() =>
  import('./components/HeavyComponent.vue')
)

加载状态

JavaScript
const AsyncComp = defineAsyncComponent({
  loader: () => import('./HeavyComponent.vue'),
  loadingComponent: LoadingSpinner,
  delay: 200,       // 延迟显示 loading
  timeout: 3000     // 超时时间
})

路由懒加载

JavaScript
const routes = [
  {
    path: '/dashboard',
    component: () => import('./views/Dashboard.vue')
  }
]

异步组件结合路由懒加载是优化首屏性能的标准做法。

要点总结

  • <component :is="..."> 实现动态组件切换
  • <keep-alive> 缓存动态组件状态
  • defineAsyncComponent 实现异步加载
  • 路由懒加载使用动态 import()
想在手机上练习这篇文章的配套题目?
使用微信卷王开发者小程序,打开首页顶部扫码功能识别二维码
← 上一篇 组件生命周期
下一篇 → 组件通信
扫码体验小程序
加载中
想在手机上刷题学习?
使用微信卷王开发者小程序,打开首页顶部扫码功能识别二维码