一文帶你深入了解V-model實現(xiàn)數(shù)據(jù)雙向綁定
父組件實現(xiàn)雙向綁定
在父組件中使用 v-model:
<ChildComponent v-model="message" />
等價于:
<ChildComponent :modelValue="message" @update:modelValue="val => message = val" />
:modelValue:通過 props 將 message 的值傳遞給子組件。
@update:modelValue:通過 emit 向父組件發(fā)送更新值。
子組件實現(xiàn)雙向綁定
為了支持父組件的 v-model,子組件需要:
1.定義 props,接收父組件傳遞的數(shù)據(jù)。
2.使用 emit 發(fā)送更新事件。
<script setup>
import { defineProps, defineEmits } from 'vue';
// 接收父組件傳遞的 modelValue
defineProps({
modelValue: String, // 父組件傳遞的值
});
// 定義更新事件
defineEmits(['update:modelValue']);
const updateValue = (newValue) => {
// 觸發(fā)事件,通知父組件更新數(shù)據(jù)
emit('update:modelValue', newValue);
};
</script>
<template>
<input :value="modelValue" @input="updateValue($event.target.value)" />
</template>
defineModel()
從 Vue 3.4 開始,推薦的實現(xiàn)方式是使用 defineModel()宏
<!-- Child.vue -->
<script setup>
const model = defineModel()
function update() {
model.value++
}
</script>
<template>
<div>Parent bound v-model is: {{ model }}</div>
<button @click="update">Increment</button>
</template>
父組件可以用 v-model 綁定一個值:
template
<!-- Parent.vue --> <Child v-model="countModel" />
defineModel() 返回的值是一個 ref。它可以像其他 ref 一樣被訪問以及修改,不過它能起到在父組件和當前變量之間的雙向綁定的作用:
- 它的 .value 和父組件的 v-model 的值同步;
- 當它被子組件變更了,會觸發(fā)父組件綁定的值一起更新。
這意味著你也可以用 v-model 把這個 ref 綁定到一個原生 input 元素上,在提供相同的 v-model 用法的同時輕松包裝原生 input 元素:
<script setup> const model = defineModel() </script> <template> <input v-model="model" /> </template>
底層機制
defineModel 是一個便利宏。編譯器將其展開為以下內(nèi)容:
一個名為 modelValue 的 prop,本地 ref 的值與其同步;
一個名為 update:modelValue 的事件,當本地 ref 的值發(fā)生變更時觸發(fā)。
到此這篇關(guān)于一文帶你深入了解V-model實現(xiàn)數(shù)據(jù)雙向綁定的文章就介紹到這了,更多相關(guān)V-model數(shù)據(jù)雙向綁定內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue登錄頁面回車執(zhí)行事件@keyup.enter.native問題
這篇文章主要介紹了vue登錄頁面回車執(zhí)行事件@keyup.enter.native問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03
Vue插件報錯:Vue.js is detected on this page.問題解決
這篇文章主要介紹了Vue插件報錯:Vue.js is detected on this page.問題解決,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-07-07
vue實現(xiàn)一個矩形標記區(qū)域(rectangle marker)的方法
這篇文章主要介紹了vue實現(xiàn)一個矩形標記區(qū)域 rectangle marker的方法,幫助大家實現(xiàn)區(qū)域標記功能,感興趣的朋友可以了解下2020-10-10

