Vue:为什么只有最后一个对象只与for循环中的每个模态相关联



这是我第一次使用模态组件。在对象数组的for循环中,我还添加了一个模态组件";添加项目";。v:onClick=";showSectionID";模态中SHOW按钮中的函数应该只控制台显示打开关联模态的对象的id,然后单击其相应的SHOW按钮。但相反,无论我在任何相关模态中单击SHOW按钮,它都会给出最后一个对象的id。

只是为了测试,我删除了整个模态,只保留了SHOW按钮,在这种情况下,它给了我正确的id。我真的不知道模态中出了什么问题,并在互联网上搜索了几个来源以查看类似的解决方案,但找不到。参见代码:

<div v-for="(section) in allDataObject['Section']" :key="section['uuid']">          
<h4>Section Name: {{ section["sectionName"] }}</h4>
<h4>Section Description: {{ section["sectionDescription"] }}</h4>
<template>
<div>
<b-button @click="modalShow = !modalShow">Add Item</b-button>
<b-modal v-model="modalShow">Fill form to add an item !
<button v-on:click="showSectionID (section['uuid'])">SHOW</button>                         
</b-modal>       
</div>
</template>
</div>

在您的代码中,您正在为for循环中的每个部分创建一个模态组件
如果你所有的模态都出现在屏幕上,我不会感到惊讶,但你会看到最后一个,因为它在所有其他模态之上。但这也取决于模态是如何实现的。

我建议您将模态模板移到for循环之外,并更改您在组件数据中存储的内容,以便您知道在模态中显示哪个部分。

假设您的数据((如下所示:

data() {
return {
modalVisible: false,
modalSectionUUID: null
}
}

然后您可以创建两种方法来显示和隐藏模态:

methods: {
showModal(sectionUUID) {
this.modalVisible = true;
this.modalSectionUUID = sectionUUID;
},
hideModal() {
this.modalVisible = false;
this.modalSectionUUID = null;
}
}

现在,你的模板最终会是这样的:

<b-modal v-model="modalVisible">Fill form to add an item !
<button v-on:click="showSectionID(modalSectionUUID)">SHOW</button>                         
</b-modal>
<div v-for="(section) in allDataObject['Section']" :key="section['uuid']">          
<h4>Section Name: {{ section["sectionName"] }}</h4>
<h4>Section Description: {{ section["sectionDescription"] }}</h4>
<template>
<div>
<b-button @click="showModal(section['uuid'])">Add Item</b-button>
</div>
</template>
</div>

最新更新