VueJs 3复选框v-model对象数组不能正常工作



我很难理解为什么我的v-model不能正常工作我有一个service对象,它包含一个IAction类型的属性actions []我还声明了一个对象actions,它是IAction的数组,我目前正试图将复选框绑定到actions数组,但它不工作。

我觉得我在这里错过了一些明显的东西,但需要一点帮助来理解它是什么。

以下是相关代码

<script lang="ts">
let actions = [] as IAction[];
</script>
<template>
<div v-for="action in service.Actions" :key="action.Id" class="row">
<div class="col-md-12 d-flex">
<div>
<span class="pe-3">
{{ action.EnumName }}
</span>
<input v-model="actions" :value="action" type="checkbox" />
</div>
</div>
</div>
</template>

我将感谢任何反馈,因为我是相对较新的VueJs,谢谢你

我想你可能不明白你在代码中做什么,所以我写了一些例子。

坏代码:

<script lang="ts">
let actions = [] as IAction[];
</script>
<template>
// here you iterate thro array and assign to action variable
<div v-for="action in service.Actions" :key="action.Id" class="row">
<div class="col-md-12 d-flex">
<div>
<span class="pe-3">
{{ action.EnumName }}
</span>
// Here you using actions with "s" on end so you using empty array declered in script
<input v-model="actions" :value="action" type="checkbox" />
</div>
</div>
</div>
</template>

如果您从service.Actions获得一些数据,请使用它们!v-model将覆盖这些动作,如果它们是ref()或' reactive()。

例子:

<script lang="ts">
let actions = [] as IAction[];
</script>
<template>
<div v-for="item in service.Actions" :key="action.Id" class="row">
<div class="col-md-12 d-flex">
<div>
<span class="pe-3">
{{ item.EnumName }}
</span>
<input v-model="item.is" :value="action" type="checkbox" />
</div>
</div>
</div>
</template>

如果service.Actions只是数组动作,你想添加到脚本的数组actionsv-model不是你这样做的方式!

可能你需要的代码:

<script lang="ts">
const actions = ref([])  // Use refs everywhere !!! A specially in forms.
function deleteItem() {
// ToDo delete item from actions array
}
</script>
<template>
<div v-for="item in service.Actions" :key="item.Id" class="row">
<div class="col-md-12 d-flex">
<div>
<span class="pe-3">
{{ item.EnumName }}
</span>
<button @click="actions = [...actions, item]">ADD</button>
</div>
</div>
</div>
<div>
<div v-for="{ item, index } in actions" :key="item.id">
<span>{{ item.EnumName }}</span><button @click="deleteItem(index)">X</button>
</div>
</div>
</template>

正如Mises所指出的,v-model必须是与v-for相同对象的一部分,所以我只是将我的服务和操作数组放在一个对象中

let foo = { services: serviceStore.services, actions: [] as IAction[] }

最新更新