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

相关推荐
@PHARAOH1 小时前
WHAT - GitLens vs Fork
前端
yqcoder1 小时前
前端性能优化:如何减少重绘与重排?
前端·性能优化
洋子2 小时前
Yank Note 系列 13 - 让 AI Agent 进入笔记工作流
前端·人工智能
wenzhangli74 小时前
Ooder A2UI 核心架构深度解析:WEB 拦截层的设计与实现
前端·架构
前端百草阁4 小时前
【前端性能优化全链路指南】从开发编写到构建运行的多维度实践
前端·性能优化
神探小白牙5 小时前
eCharts 多系列柱状图增加背景图
javascript·ecmascript·echarts
女生也可以敲代码5 小时前
AI时代下的50道前端开发面试题:从基础到大模型应用
前端·面试
ZhengEnCi5 小时前
M5-markconv自定义CSS样式指南 📝
前端·css·python
IT_陈寒5 小时前
SpringBoot自动配置的坑差点让我加班到天亮
前端·人工智能·后端
xingpanvip5 小时前
星盘接口开发文档:星相日历接口指南
android·开发语言·前端·css·php·lua