全部学科
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()

📝 发现内容有误?点击此处直接编辑

← 上一篇 计算属性的缓存特性
下一篇 → 插槽
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库