v-for checkbox value in child component as prop (array of objects)(V-表示作为道具(对象数组)的子组件中的复选框值)
问题描述
我有两个组件‘Parent’和‘Child’。每个辅元件都有复选框:选中道具。在父组件中,我迭代对象数组并将道具传递给子组件。我可以将事件从子元素发送回父元素,并在数组中重新分配新值,但组件不会重新呈现。
我试图做的是获得一些无线电群体行为,但不在复选框内。当单击一个复选框时,需要将其他复选框设置为False。我可以清楚地看到数组已被修改,但组件未重新呈现( 这是沙盒链接 https://codesandbox.io/s/vue-starter-forked-jxgf9?fontsize=14&hidenavigation=1&theme=dark
父组件:
<template>
<div>
<Child
v-for="l in list"
:id="l.id"
:key="l.id"
:title="l.title"
:checked="l.checked"
@checked="handleUpdate"
/>
</div>
</template>
<script>
import Child from "../components/Child.vue";
export default {
name: "parent",
components: {
Child
},
data: () => ({
list: [
{ title: "First", checked: false, id: "01" },
{ title: "Second", checked: false, id: "02" },
{ title: "Third", checked: false, id: "03" },
{ title: "Fourth", checked: false, id: "04" },
{ title: "Fifth", checked: false, id: "05" }
]
}),
methods: {
handleUpdate(e) {
const newArray = this.list.map(a => ({ ...a }));
console.log(newArray);
newArray.forEach(el => {
if (el.id === e) {
el.checked = true;
} else {
el.checked = false;
}
});
this.list = [];
this.list = newArray;
}
}
};
</script>
子组件:
<template>
<div>
<h1>{{ title }}</h1>
<input type="checkbox" :value="checked" @click="$emit('checked', id)">
</div>
</template>
<script>
export default {
name: "child",
props: {
title: {
type: String,
required: true
},
checked: {
type: Boolean,
required: true
},
id: {
type: String,
required: true
}
}
};
</script>
任何帮助都是非常感谢的家伙。我真的坚持了下来,我压力很大(
推荐答案
来自MDN: Checkbox: Additional attributes,
Attribute Description
checked Boolean; if present, the checkbox is toggled on by default
indeterminate A Boolean which, if present, indicates that the value of the checkbox is indeterminate rather than true or false
value The string to use as the value of the checkbox when submitting the form, if the checkbox is currently toggled on
因此,在您的代码中,Child.vue内的v-bind:valuefor<input type="checkbox">不会切换复选框,它只在提交表单时更改复选框的值。
来自Vue Guide::声明如下:
V-Model在内部使用不同的属性并发出不同的 不同输入元素的事件:文本和文本区域元素使用Value属性和输入事件;
复选框和单选按钮使用选中的属性和更改事件;
选择字段使用值作为道具,将更改作为事件。
这就是v-model的工作方式。
so在Child.vue中使用:
<input type="checkbox" :checked="checked" @click="$emit('checked', id)">
Updated Code SandBox
这篇关于V-表示作为道具(对象数组)的子组件中的复选框值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:V-表示作为道具(对象数组)的子组件中的复选框值
基础教程推荐
- 即使每次插入第一个输入的值不同,第二个输入仍显示相同的输入值 2022-01-01
- HTML5 画布调整为父级 2022-01-01
- CORS:当凭据标志为真时,无法在 Access-Control-Allow-Origin 中使用通配符 2022-01-01
- 使用 jQuery 在悬停时交换 DIV 类 2022-01-01
- 在 Javascript 中使用 Fetch API 上传文件并显示进度 2022-01-01
- 最佳动态 JavaScript/JQuery 网格 2022-01-01
- 从快速中间件中排除路由 2022-01-01
- 带角度的选项卡:仅使用 $http 在单击时加载选项卡 2022-01-01
- 逻辑运算符 ||在 javascript 中,0 代表 Boolean false? 2022-01-01
- 当木偶师打开Chrome时,不能使用Chrome扩展 2022-01-01
