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