Vue.js如何通过子组件的v-model实现数组类型数据的追加
问题分析
- 原实现逻辑不符合Vue复选框组绑定数组的规范:多个复选框收集选中值到数组时,v-model需要绑定整个数组,而非数组的单个下标元素,原写法每个子组件仅修改对应下标的值,无法实现自动追加/移除选中值的效果
- 子组件的事件逻辑缺失状态判断:仅emit复选框的值,没有区分选中/取消状态,无法判断要追加还是移除值
- 原代码存在两处笔误:组件注册属性
component应为复数components,data中定义的变量gameModeNames和模板中使用的gameModesNames命名不一致
修正后代码
父组件
<template> <h1> {{gameModes}}</h1> <Child v-for="(value, index) in gameModeNames" v-bind:key="index" :name="value" v-model="gameModes" /> </template> <script> import Child from './Child.vue'; export default { components: { Child }, data() { return { gameModes: [], gameModeNames: ["bullet" ,"blitz" , "rapid"] } } } </script>
子组件
<template> <div> <input type="checkbox" :id="name" :value="name" :checked="value.includes(name)" @change="handleChange" /> <label :for="name">{{name}}</label> </div> </template> <script> export default { props: { name: String, value: Array }, methods: { handleChange(e) { const updatedArr = [...this.value] if (e.target.checked) { updatedArr.push(this.name) } else { const targetIndex = updatedArr.findIndex(item => item === this.name) if (targetIndex > -1) updatedArr.splice(targetIndex, 1) } this.$emit('input', updatedArr) } } } </script>
核心修改说明
- 父组件将v-model绑定到整个
gameModes数组,所有子组件共享同一个选中状态数据源 - 子组件新增接收父组件传入的选中数组,通过判断当前name是否在数组中设置复选框的选中状态
- 子组件监听change事件,根据选中状态更新数组后同步给父组件,实现双向绑定
内容的提问来源于stack exchange,提问作者hexaquark
相关产品推荐
相关产品推荐

