You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在父组件中通过点击按钮动态添加子组件

动态增加父组件中子组件数量的实现方案

核心逻辑是在父组件中维护一个响应式数组,通过v-for循环渲染子组件,点击按钮时向数组添加元素触发视图更新,从而新增子组件实例。

Vue 3 实现示例

父组件(AppParent.vue)

<template>
  <div class="app-parent">
    <button @click="addChild">新增子组件</button>
    <!-- 循环渲染子组件,绑定唯一key -->
    <app-child v-for="(_, index) in childList" :key="index"></app-child>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import AppChild from './AppChild.vue'

// 初始化数组,对应初始的1个子组件
const childList = ref([1])

// 新增子组件的方法
const addChild = () => {
  childList.value.push(1)
}
</script>

子组件(AppChild.vue)

<template>
  <div class="app-child">
    我是子组件
  </div>
</template>

Vue 2 实现示例

父组件(AppParent.vue)

<template>
  <div class="app-parent">
    <button @click="addChild">新增子组件</button>
    <app-child v-for="(_, index) in childList" :key="index"></app-child>
  </div>
</template>

<script>
import AppChild from './AppChild.vue'

export default {
  components: { AppChild },
  data() {
    return {
      childList: [1]
    }
  },
  methods: {
    addChild() {
      this.childList.push(1)
    }
  }
}
</script>

子组件代码与Vue 3示例一致

关键注意点

  • v-for必须绑定唯一的:key属性,示例中使用数组索引,实际项目建议使用具有唯一性的标识(如UUID),避免渲染异常
  • 依赖Vue的响应式机制,直接修改数组(如push、pop)会自动触发视图更新
  • 数组元素仅作为渲染标识,可根据业务需求存储子组件的配置数据(如子组件需要的props参数)

内容的提问来源于stack exchange,提问作者user6781

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 02:12:18