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

为什么我的Modal组件无法获取正确的props属性值?

问题原因

你在列表中循环渲染多个<DeleteModal>组件时,所有组件内的Modal弹窗都使用了固定的相同idremoveModal,触发按钮也都绑定了同一个data-bs-target="#removeModal"。
Bootstrap的Modal触发逻辑是根据target选择器匹配DOM,同id选择器永远只会命中页面上第一个渲染的对应元素,所以无论你点击哪一行的删除按钮,弹出的始终是第一个被渲染的Modal实例,这个实例对应的eventIndex就是初始的0值。你在按钮点击事件里打印的是当前点击组件实例的props值,所以日志输出是正确的,但弹出的Modal不属于当前点击的组件实例。

点击按钮后弹出的模态框,对应正确eventIndex值为2

修复方案

给每个组件内的Modal和对应触发按钮生成唯一的绑定标识,用传入的eventIndex拼接id即可,修改后的代码如下:

<template>
  <button
    type="button"
    class="btn btn-close"
    data-bs-toggle="modal"
    :data-bs-target="`#removeModal-${eventIndex}`"
    aria-label="Remove"
    @click="test"
  ></button>

  <div class="modal fade" :id="`removeModal-${eventIndex}`" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Remove Event</h5>
          <button
            type="button"
            class="btn-close"
            data-bs-dismiss="modal"
            aria-label="Close"
          ></button>
        </div>
        <div class="modal-body">
          Are you sure that you want to remove this event from this csv file?
          This process cannot be resumed.
          eventIndex: {{ eventIndex }}
        </div>
        <div class="modal-footer">
          <button
            type="button"
            class="btn btn-secondary"
            data-bs-dismiss="modal"
            @click="test"
          >
            Cancel
          </button>
          <button
            type="button"
            class="btn btn-primary"
            data-bs-dismiss="modal"
            @click="remove_event"
          >
            Remove
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
export default {
  props: ["eventIndex"],
  methods: {
    test() {
      console.log(this.eventIndex);
    },
    remove_event() {
      //...
    },
  },
};
</script>

<style scoped></style>
额外注意点
  • 模板里插值直接写{{ eventIndex }}即可,不需要加this.,模板上下文默认绑定组件实例
  • 如果你的列表数据有唯一主键,优先用主键代替index拼接Modal id,避免列表排序、增删时index变化导致匹配错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 09:36:25