我刚开始使用Vue3 (composition API)和bootstrap 5,遇到了一个问题:
当我渲染一个列表,并传递每个元素作为一个prop:
<div :key="item.id" v-for="item in items">
<EditItem :item="item"/>
</div>
我可以修改EditItem.vue
内的道具值(道具是JSON对象),但是当我在一个模态我只能修改第一个索引的值。我的代码看起来像这样:
<script setup>
defineProps({
item: {
type: Object,
required: true
},
})
</script>
<template>
<!-- Let's me edit all items in list just fine -->
<input type='text' v-model="item.name">
<div> {{item.name}} </div>
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
Edit Item
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="exampleModalLabel">Modal title</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="mb-3">
<!-- Will only let me edit the first indexed list item -->
<label for="name" class="form-label">Item name</label>
<input type='text' class="form-control" id="name" placeholder="John Doe" v-model="item.name">
<div> {{ item.name }} </div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
</template>
认为这是因为模态被视为不同的文档/上下文,所以ve3重新呈现所有内容,所以索引从1重新开始。我不知道如何解决这个问题,任何帮助都很感激。由于
编辑:我的问题类似于这个问题中描述的问题:如何在使用Vue.js时显示新的引导模态数据
然而,它没有得到正确的回答,是2018年的
编辑2:
解决:这是一个简单的修复,只需将模态从v-for循环中取出。只有按钮在循环内。是的,我意识到你不能在子组件中编辑prop的值。我简化了代码,因为我的JSON对象中有许多字段,所以我的表单代码很长。
Props是只读的。为了能够编辑数组,您需要在拥有该数组的地方发出delete函数。你的"让我编辑所有项目"也不工作。它只是编辑一个局部变量,而不是一个数组。
这是如何创建可重用表单:
form.vue
<template>
<form @submit.prevent="$emit('onSubmit', data)">
<input type="text" v-model="data.name" />
<button type="submit">Save</button>
</form>
</template>
<script setup>
const props = defineProps({ item: { type: Object, required: true }})
const data = reactive(props.item)
defineEmits(['onSubmit'])
</script>
parent.vue
<template>
<form :item="item" @on-submit="editItem"></form>
</template>
<script setup>
function editItem(data) {
// Edit array here.
}
</stript>