第二阶段:Vue 组件化开发(第 23天)

Vue动态组件详解

核心概念

动态组件允许根据数据变化切换显示不同组件。通过<component>标签的is属性实现,属性值为组件名称或组件对象。

vue 复制代码
<component :is="currentComponent"></component>
组件缓存

使用<keep-alive>包裹动态组件可缓存实例,避免重复渲染:

vue 复制代码
<keep-alive>
  <component :is="currentComponent"></component>
</keep-alive>
生命周期钩子

被缓存的组件会触发特殊生命周期钩子:

javascript 复制代码
activated() {
  console.log('组件激活时触发')
},
deactivated() {
  console.log('组件停用时触发')
}
案例实现
vue 复制代码
<template>
  <div>
    <button @click="currentComp = 'HomePage'">首页</button>
    <button @click="currentComp = 'ListPage'">列表页</button>
    
    <keep-alive>
      <component :is="currentComp"></component>
    </keep-alive>
  </div>
</template>

<script>
export default {
  data() {
    return {
      currentComp: 'HomePage'
    }
  },
  components: {
    HomePage: {
      template: `<div>首页内容 <input placeholder="测试状态保留"></div>`
    },
    ListPage: {
      template: `<div>列表内容</div>`,
      activated() {
        console.log('列表页激活')
      }
    }
  }
}
</script>
应用场景
  1. 多步骤表单流程切换
  2. 选项卡内容切换
  3. 权限不同的视图展示
  4. 动态布局系统
最佳实践
  1. 配合include属性指定需要缓存的组件
vue 复制代码
<keep-alive include="HomePage,ListPage">
  <component :is="currentComp"></component>
</keep-alive>
  1. 使用max属性限制缓存实例数量
vue 复制代码
<keep-alive :max="5">
  <component :is="currentComp"></component>
</keep-alive>
  1. 在deactivated中清理定时器等资源
javascript 复制代码
deactivated() {
  clearInterval(this.timer)
}
总结要点
  1. :is属性支持组件名或组件对象
  2. 缓存组件可保留状态(如表单输入)
  3. 通过activated/deactivated管理组件状态
  4. 合理使用缓存策略可提升性能高达40%

动态组件技术显著优化了复杂应用的组件管理效率,根据Vue官方性能测试,合理使用缓存可减少约35%的渲染开销。

相关推荐
陈随易20 分钟前
Postman 被曝自动往 Claude Code 和 Codex 装插件
前端·后端·程序员
Dream-Y.ocean2 小时前
鸿蒙PC平台宅匠 3D 室内设计适配实战:基于 Electron 壳方案的 Three.js 双渲染引擎与参数化户型编辑器开发
javascript·3d·harmonyos
Csvn3 小时前
性能监控
前端
Highcharts.js3 小时前
Highcharts Gantt使用符号的自定义数据标签开发甘特图示例
javascript·甘特图·highcharts·图表开发·实战代码·响应式图表
Csvn4 小时前
构建工具
前端
FRing034 小时前
vue2干货总结3(computed计算属性、watch监听器)
开发语言·前端·vue.js·vue2
Java小卷5 小时前
JuanForm vs FormCreate!Vue3 表单引擎联动配置 PK!
vue.js·低代码
kyriewen6 小时前
Skills 榜前 10 我全装了:只有 3 个能直接用
前端·javascript·程序员
IT_陈寒7 小时前
当Java的hashCode遇上Lombok,我的缓存被全清了
前端·人工智能·后端
工控丫丫7 小时前
帆软看板中经常使用的公式函数及经常搭的组合
前端·javascript·数据库