Vue3 defineModel 完全指南:用法 + 場(chǎng)景 + 原理

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" />
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容