checkbox - 当值相同的vuejs时,多个复选框不起作用
问题描述
当我检查苹果时,所有检查都是菠萝。当我取消选中 Pineapple 时,它也未选中 Apple。两个标签 ID 不同。我怎样才能只检查一个苹果而不是菠萝?
var demo = new Vue({
el: '#demo',
data: {
checkedNames: []
},
computed: {
computedNames() {
let names = this.checkedNames;
return names.toString();
}
}
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<div id="demo">
<input type="checkbox" id="50" value="50" v-model="checkedNames">
<label for="Apple">Apple</label>
<input type="checkbox" id="51" value="51" v-model="checkedNames">
<label for="Banana">Banana</label>
<input type="checkbox" id="52" value="50" v-model="checkedNames">
<label for="Pineapple">Pineapple</label>
<br>
<span>Checked names: {{ checkedNames }}</span>
<span>Computed names (reversed order): {{ computedNames }}</span>
</div>
解决方案
Vue 是数据驱动的。由于您的Apple和Pineapple复选框具有相同的value
,因此 Vue 认为它们是相同的。
听起来你想完全使用单独的对象,所以试试这个
var demo = new Vue({
el: '#demo',
data: () => ({
options: [{
id: 50,
label: "Apple",
price: 50
}, {
id: 51,
label: "Banana",
price: 51
}, {
id: 52,
label: "Pineapple",
price: 50
}],
selections: []
}),
computed: {
computedNames: ({ selections }) =>
selections.map(({ label }) => label).join(", ")
}
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<div id="demo">
<template v-for="fruit in options">
<input
:key="fruit.id"
type="checkbox"
:value="fruit"
v-model="selections"
:id="`fruit_${fruit.id}`"
>
<label :for="`fruit_${fruit.id}`">{{ fruit.label }}</label>
</template>
<br>
<span>Computed names: {{ computedNames }}</span>
<pre>Selections: {{ selections }}</pre>
</div>
推荐阅读
- javascript - 表单生成器 - 无法读取未定义的属性“获取”,验证器存在问题
- linq - LINQ orderby 不在瑞典文化中工作
- php - foreach 类别回显结果
- python - Selenium - 在检查 HTML 之前找不到可见元素?
- ios - 错误:无法分配类型“字符串?”的值 键入“字符串?。类型”
- python-3.x - 按分隔符将列表拆分为子列表
- visual-studio - 在 TFS 中签入时从 Visual Studio 中恢复已删除的文件/代码
- php - 警告:file_exists() 期望参数 1 是有效路径,数组在 C:\
- mediawiki - 条件类别
- javascript - 如何使用 ASP.NET 从 MSSQL 中获取 JQuery 自动完成小部件的数据