如何让2个子组件更新同一个父属性?

问题描述 投票:0回答:1

我想使用复选框根据其类别过滤一些产品。

为此,我有一个父组件,它将可能的类别(例如 A、B 和 C)传递给子组件并跟踪选中/选定的类别:

Parent.vue

<template>
  <FilterCheckboxItem
    ref="Category"
    name="Category"
    :FilterOptions="CategoryOptions"
    v-model="FilteredCategories"
  />
</template>

<script>


export default {
    data(){
        return {
          FilteredCategories: [],
          CategoryOptions: ["A","B","C"]
         }
    }
</script>

子组件看起来像这样(简化):

FilterCheckboxItem.vue

<template>
<div
  v-for="FilterOption in FilterOptions"
>
  <input
    type="checkbox"
    :value="FilterOption"
    v-model="checked"
  />
</div>
</template>

<script>

export default {
    props: {
     FilterOptions: {
      type: Array,
    },
    modelValue: {
      type: Array,
    },
 },

  emits: ['update:modelValue'],


  setup(props, { emit }) {
    const checked = ref([]);
    watch(checked, (newVal) => {
      emit('update:modelValue', newVal);
    });
    return { emit, checked };
  },

</script>

这按预期工作。

但是,当我想再次添加相同的子组件时(例如普通菜单中的 1 个筛选按钮和移动菜单中的 1 个),2 个子组件中的数组不再对齐。例如,我在第一个子组件上选择类别“A”,那么第二个子组件未正确更新(类别“A”)将不会被检查。

如何确保每当我更改第一个子组件中的某些内容时,它都会更新父组件,同时确保第二个子组件正确更新?

我希望这能起作用,因为它们被引用到相同的 v-model 属性。

vuejs3 vue-component
1个回答
0
投票

父组件中的 v 模型(在子组件中以

modelValue
形式存在)与实际输入中使用的 v 模型(
checked
)不同。当
checked
更新时,您使用观察者来更新父 v-model。当 v-model 更新时,没有等效的代码来更新
checked
,但也没有必要。只需使用
modelValue
作为输入上的 v 模型即可。根本不需要
checked
或观察者。

FilterCheckboxItem.vue

<template>
<div
  v-for="(FilterOption, index) in FilterOptions"
> 
  <label for="lname">{{FilterOption}}</label>   
  <input
    type="checkbox"
    :value="FilterOption"
    v-model="modelValue[index]"
  />
</div>
</template>
<script>
export default {
    props: {
     FilterOptions: {
      type: Array,
    },
    modelValue: {
      type: Array,
    },
 },
}
</script>

Vue Playground 示例

© www.soinside.com 2019 - 2024. All rights reserved.