第二阶段: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%的渲染开销。

相关推荐
qq_20815408853 分钟前
瑞树6代流程分析
javascript·python
UXbot6 分钟前
AI原型设计工具评测:从创意到交互式Demo,5款产品全面解析
前端·ui·设计模式·ai·ai编程·原型模式
落魄江湖行7 分钟前
硅基同事埋的坑,我用2小时才填平:Nuxt 4 路由踩坑:可选参数 [[id]] 与 [id] 的区别
前端
一勺菠萝丶13 分钟前
管理后台使用手册在线预览与首次登录引导弹窗实现
java·前端·数据库
军军君0114 分钟前
Three.js基础功能学习十四:智能黑板实现实例一
前端·javascript·css·typescript·前端框架·threejs·智能黑板
小村儿16 分钟前
连载05-Claude Skill 不是抄模板:真正管用的 Skill,都是从实战里提炼出来的
前端·后端·ai编程
xiaotao13122 分钟前
JS new 操作符完整执行过程
开发语言·前端·javascript·原型模式
robch29 分钟前
python3 -m http.server 8001直接启动web服务类似 nginx
前端·nginx·http
吴声子夜歌35 分钟前
ES6——数组的扩展详解
前端·javascript·es6
guhy fighting44 分钟前
new Map,Array.from,Object.entries的作用以及使用方法
开发语言·前端·javascript