defineModel 是 Vue 3.4+ 官方推出的語(yǔ)法糖,專門用來(lái)簡(jiǎn)化自定義組件的 v-model 雙向綁定,讓代碼少寫 50%,是 Vue3 開發(fā)必學(xué)神器!
一、核心作用(一句話記?。?/h3>
不用再寫 props + emit 手動(dòng)實(shí)現(xiàn)雙向綁定了,一行代碼搞定組件 v-model
二、基礎(chǔ)用法(對(duì)比傳統(tǒng)寫法,一眼看懂)
1. 傳統(tǒng) v-model(麻煩版)
需要手動(dòng)接收 modelValue、觸發(fā) 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(極簡(jiǎn)版 ?)
直接當(dāng)成普通變量用,自動(dòng)實(shí)現(xiàn)雙向綁定
<!-- 子組件 -->
<template>
<!-- 直接用,不用管 props 和 emit! -->
<input v-model="model" />
</template>
<script setup>
// 一行代碼 = props + emit
const model = defineModel()
</script>
父組件使用完全不變,還是正常寫
<Child v-model="value" />