defineModel 是 Vue 3.4+ 官方推出的语法糖,专门用来简化自定义组件的 v-model 双向绑定,让代码少写 50%,是 Vue3 开发必学神器!
一、核心作用(一句话记住)
不用再写 props + emit 手动实现双向绑定了,一行代码搞定组件 v-model
二、基础用法(对比传统写法,一眼看懂)
1. 传统 v-model(麻烦版)
需要手动接收 modelValue、触发 update:modelValue
<!-- 子组件 -->
<template>
<input :value="modelValue" @input="$emit('update:modelValue', $event.target.value)" />
</template>
<script setup>
const props = defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])
</script>
2. defineModel(极简版 ✅)
直接当成普通变量用,自动实现双向绑定
<!-- 子组件 -->
<template>
<!-- 直接用,不用管 props 和 emit! -->
<input v-model="model" />
</template>
<script setup>
// 一行代码 = props + emit
const model = defineModel()
</script>
父组件使用完全不变,还是正常写
<Child v-model="value" />