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

Vue多次复用相同子组件时点击事件触发仅展开对应关联组件问题咨询

核心问题

你当前使用单一布尔类型变量editCard控制所有表单的显隐,只要该变量为true,所有绑定了v-if="this.editCard"的表单都会同时展示,这是问题的根本原因。

解决方案

你需要给每个卡片设置唯一标识,点击编辑时传递当前卡片的标识到父组件,父组件仅展示和当前标识匹配的表单即可。


第一步:修改子组件Card.vue

新增唯一标识prop,点击编辑时将该标识传递给父组件:

<template>
  <div class="card mb-1 p-1">
    <div class="d-flex justify-content-space-between">
        <h3>{{ title }}</h3>
        <span @click="editCard"><i class="material-icons">mode_edit</i></span>
    </div>
    <p class="m-0">{{ content }}</p>
  </div>
</template>
<script>
export default {
  name: 'Card',
  // 新增cardKey作为卡片唯一标识
  props: ['title', 'content', 'cardKey'],
  methods: {
    editCard () {
      // 传递当前卡片的唯一标识给父组件
      this.$emit('clicked', this.cardKey)
    }
  }
}
</script>

第二步:修改父组件代码

调整状态存储逻辑,根据标识判断对应表单是否展示:

<template>
<div>
    <!-- 给每个卡片传入对应的唯一标识 -->
    <Card 
      title="E-mail address" 
      content="test@test.com" 
      cardKey="address"
      @clicked="onClickChild"
    ></Card>
    <Address v-if="editActiveKey === 'address'" />
    <hr>
    <Card 
      title="Shipping method" 
      content="Post 5 dollar" 
      cardKey="shipment"
      @clicked="onClickChild"
    ></Card>
    <Shipment v-if="editActiveKey === 'shipment'" />
    <hr>
    <Card 
      title="Payment method" 
      content="Bank by wire" 
      cardKey="payment"
      @clicked="onClickChild"
    ></Card>
    <Payment v-if="editActiveKey === 'payment'" />
    <hr>
    <Terms></Terms>
  </div>
</template>
<script>
import Address from './forms/Address';
import Shipment from './forms/Shipment';
import Payment from './forms/Payment';
import Terms from './Terms';
import Card from './Card';
export default {
  name: 'OPC',
  components: {
    Address,
    Shipment,
    Payment,
    Terms,
    Card
  },
  data() {
    return {
      // 存储当前激活编辑状态的卡片标识,默认空
      editActiveKey: ''
    }
  },
  methods: {
    onClickChild (key) {
      // 赋值当前点击的卡片标识
      this.editActiveKey = key
    }
  }
};
</script>

拓展说明

如果需要实现点击其他区域/提交表单后关闭编辑态,只需要在对应逻辑中将editActiveKey赋值为空字符串即可。

内容的提问来源于stack exchange,提问作者R-b-n

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 20:57:05