将 v-model 传递到 Vue 3 组件内的复选框中?

Passing v-model into a checkbox inside a Component in Vue 3?

我想在 Vue3 组件中嵌入一个复选框,并将 v-model 绑定传递给该复选框。

组件内部:

<!-- Tile.vue -->
<template>
  <div>
    <input type=checkbox v-model="$attrs">
  </div>
</template>
<script>
export default {inheritAttrs: false}
</script>

然后在外部文件中:

<template>
<Tile value="carrot" v-model="foods" />
<Tile value="tomatoes" v-model="foods" />
</template>
<script setup>
var foods = ref([]);
</script>

我该如何实现?

文档说 v-model 只是 :modelValue@update:modelValue 的 shorthand 但这并不普遍,因为 Vue 显然对表单元素(例如 smartly)表现不同监听 onchange 而不是 oninput 并根据节点修改 属性 checked 而不是 value

如果我在外部组件上使用 v-model,我如何将它转发到复选框并获得与 Vue 相同的智能行为?

您可以通过使用 emits 来保持数据同步并作为默认的 v-model 行为来实现该行为。复选框组件:

<template>
  <div>
    <input
      type="checkbox"
      :checked="value"
      @change="$emit('input', $event.target.checked)"
    />
    {{ text }}
  </div>
</template>

<script>
export default {
  name: "inputcheckbox",
  props: ["value", "text"],
};
</script>

并且在父组件中,您可以拥有任意数量的复选框。

<template>
  <div id="app">
    <maincontent :showContent="showContent" />
    <inputcheckbox text="one" v-model="checkedOne" />
    <inputcheckbox text="two" v-model="checkedTwo" />
  </div>
</template>

这是一个 vue 2 示例,但也适用于 vue 3。希望这对您有所帮助。具有此行为的沙盒:

https://codesandbox.io/embed/confident-buck-kith5?fontsize=14&hidenavigation=1&theme=dark

我发现了大量有争议的信息。有些人建议使用 @input 事件 (). Some recommend emitting modelValue:update instead of update:modelValue (https://github.com/vuejs/core/issues/2667#issuecomment-732886315)。等等。经过一小时的试验和错误后,以下对我有用 Vuejs3

Child

<template>
  <div class="form-check noselect">
    <input class="form-check-input" type="checkbox" :id="id" :checked="modelValue" @change="$emit('update:modelValue', $event.target.checked)" />
    <label class="form-check-label" :for="id"><slot /></label>
  </div>
</template>

<script>
import { v4 as uuidv4 } from "uuid";

export default {
  inheritAttrs: false,
  emits: ["update:modelValue"],
  props: {
    modelValue: {
      type: Boolean,
      required: true,
    },
  },
  setup() {
    return {
      id: uuidv4(),
    };
  },
};
</script>

Parent:

<Checkbox v-model="someVariable">Is true?</Checkbox>

您可以验证它是否有效,但在 parent:

中执行此操作
    var someVariable= ref(false);

    watch(someVariable, () => {
      console.log(someVariable.value);
    });

p.s。上面的其他解决方案对我不起作用。作者推荐使用 value 属性。但在示例中,他传递了 v-model 属性。所以我不知道它应该如何工作。