vue 中的 v-model詳解
v-model 是 vue 的主要特性,雙向綁定是響應(yīng)式變量的核心。v-model 的簡單原理就是數(shù)據(jù)監(jiān)聽加UI通知,如何在我們自己的組件中實現(xiàn) v-model 呢?數(shù)據(jù)變更監(jiān)聽加父組件事件通知,如下,來自官網(wǎng)的一個例子
<script setup> const props = defineProps(['modelValue']) const emit = defineEmits(['update:modelValue']) </script> <template> <input :value="props.modelValue" @input="emit('update:modelValue', $event.target.value)" /> </template>
綁定props.modelValue
父組件使用 v-model 時會自動將父組件 v-model 對應(yīng)的變量轉(zhuǎn)換為子組件的一個屬性(props) modelValue,子組件可以通過 Props 進(jìn)行讀取
數(shù)據(jù)變更時進(jìn)行通知
通過 update:modelValue 通知父組件數(shù)據(jù)已經(jīng)更新
父組件中進(jìn)行調(diào)用
<!-- Parent.vue --> <Child :modelValue="foo" @update:modelValue="$event => (foo = $event)" />
Vue3中的簡化寫法
可以看到 v-model 中我們需要定義數(shù)據(jù)監(jiān)聽和變更通知,為什么不能直接在子組件中使用 v-model 呢,這是由于 props 變量是單向的、只讀的,子組件中不能更改。Vue3 提供了一個新的寫法,通過 defineModel 定義 v-model 屬性,如下:
<script setup> const model = defineModel() </script> <template> <input v-model="model" /> </template>
v-model 自定義變量名
默認(rèn) v-model 對應(yīng)變量名為 modelValue,在 vue3 我們也可以指定變量名,這樣父組件可以傳遞多個 v-model 變量,如下:
<script setup> const title = defineModel('title') </script> <template> <input type="text" v-model="title" /> </template>
父組件中調(diào)用時,需要制定變量名
<MyComponent v-model:title="bookTitle" />
總結(jié)
v-model 核心就是監(jiān)聽和通知,本文使用了官網(wǎng)的例子進(jìn)行了簡單的介紹,更多高級用法可以到官網(wǎng)進(jìn)行學(xué)習(xí)。
到此這篇關(guān)于vue 中的 v-model的文章就介紹到這了,更多相關(guān)vue 中的 v-model內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vuejs前后端數(shù)據(jù)交互之從后端請求數(shù)據(jù)的實例
今天小編就為大家分享一篇vuejs前后端數(shù)據(jù)交互之從后端請求數(shù)據(jù)的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08Vue3中的?computed,watch,watchEffect的使用方法
這篇文章主要介紹了Vue3中的?computed,watch,watchEffect的使用方法,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價價值,需要得小伙伴可以參考一下2022-06-06vue3中require報錯require is not defined問題及解決
這篇文章主要介紹了vue3中require報錯require is not defined問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06Vue3項目中配置TypeScript和JavaScript的兼容
在Vue3開發(fā)中,常見的使用JavaScript(JS)編寫代碼,但也會有調(diào)整編寫語言使用TypeScript(TS)的需求,因此,在Vue3項目設(shè)置中兼容TS和JS是刻不容緩的重要任務(wù),2023-08-08uniapp+vue3路由跳轉(zhuǎn)傳參的實現(xiàn)
本文主要介紹了uniapp+vue3路由跳轉(zhuǎn)傳參的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-11-11