Skip to content
On this page

2022-11-v-model的原理

1. 需求场景

v-model实现了表单和对象的双向绑定,有时候我们会想他是怎么实现的,想antd的form.item都有value和onchange事件。

2. 相关文档

3. 原生表单

shell
<input
  :value="text"
  @input="event => text = event.target.value">
  • 文本类型的 <input /><textarea /> 元素会绑定 value property 并侦听 input 事件;
  • <input type="checkbox" /><input type="radio" /> 会绑定 checked property 并侦听 change 事件;
  • <select /> 会绑定 value property 并侦听 change 事件

4. 自定义组件

实现modelValue和update:modelValue的props即可。

shell
// count.vue
<template>
  <div>
    <button @click="handleSub">-</button>
    <span>{{ props.modelValue }}</span>
    <button @click="handleAdd">+</button>
  </div>
</template>
<script lang="ts" setup>
import { defineProps, defineEmits } from "vue";
const props = defineProps(["modelValue"]);
const emits = defineEmits(["update:modelValue"]);
const handleSub = () => {
  if (isNaN(props.modelValue)) {
    emits("update:modelValue", 0);
  } else {
    emits("update:modelValue", props.modelValue - 1);
  }
};
const handleAdd = () => {
  if (isNaN(props.modelValue)) {
    emits("update:modelValue", 0);
  } else {
    emits("update:modelValue", props.modelValue + 1);
  }
};
</script>

使用

shell
<Count v-model="count" />

const count = ref(0);

Released under the MIT License.