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

相关推荐
达子6662 分钟前
第10章_HarmonyOs开发图解 用JS开发UI
vue.js
先吃饱再说17 分钟前
React 组件通信:从 Props 单向传递到自定义事件
前端·react.js·前端框架
swipe21 分钟前
05|(前端转后全栈)不手写一堆 SQL,后端怎么操作数据库?MyBatis-Plus 入门
前端·后端·全栈
Allshadow22 分钟前
Nest.js - 连接数据库
javascript·nestjs
冰暮流星26 分钟前
javascript之date对象
开发语言·javascript·ecmascript
swipe26 分钟前
04|(前端转后全栈)前端状态为什么不够用?从页面数据到 MySQL 持久化
前端·后端·全栈
橘子星27 分钟前
别光看教程!手把手拆解 React Todo 项目,一文吃透 5 个核心概念
前端·javascript
奶糖 肥晨32 分钟前
想return数据 返回的确是函数问题处理
vue.js
大白要努力!33 分钟前
纯前端实现 PDF 加水印工具 —— 零后端、支持中文、实时预览
前端·pdf·html
石小石Orz35 分钟前
TRAE SOLO实战:实现一个桌面3D助手
前端·人工智能