欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

一文帶你深入了解V-model實(shí)現(xiàn)數(shù)據(jù)雙向綁定

 更新時(shí)間:2024年12月20日 10:38:14   作者:帶錢(qián)跑路77  
這篇文章主要為大家詳細(xì)介紹了V-model實(shí)現(xiàn)數(shù)據(jù)雙向綁定的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

父組件實(shí)現(xiàn)雙向綁定

在父組件中使用 v-model:

<ChildComponent v-model="message" />

等價(jià)于:

<ChildComponent :modelValue="message" @update:modelValue="val => message = val" />

:modelValue:通過(guò) props 將 message 的值傳遞給子組件。

@update:modelValue:通過(guò) emit 向父組件發(fā)送更新值。

子組件實(shí)現(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 開(kāi)始,推薦的實(shí)現(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 綁定一個(gè)值:

template

<!-- Parent.vue -->
<Child v-model="countModel" />

defineModel() 返回的值是一個(gè) ref。它可以像其他 ref 一樣被訪問(wèn)以及修改,不過(guò)它能起到在父組件和當(dāng)前變量之間的雙向綁定的作用:

  • 它的 .value 和父組件的 v-model 的值同步;
  • 當(dāng)它被子組件變更了,會(huì)觸發(fā)父組件綁定的值一起更新。

這意味著你也可以用 v-model 把這個(gè) ref 綁定到一個(gè)原生 input 元素上,在提供相同的 v-model 用法的同時(shí)輕松包裝原生 input 元素:

<script setup>
const model = defineModel()
</script>

<template>
  <input v-model="model" />
</template>

底層機(jī)制

defineModel 是一個(gè)便利宏。編譯器將其展開(kāi)為以下內(nèi)容:

一個(gè)名為 modelValue 的 prop,本地 ref 的值與其同步;

一個(gè)名為 update:modelValue 的事件,當(dāng)本地 ref 的值發(fā)生變更時(shí)觸發(fā)。

到此這篇關(guān)于一文帶你深入了解V-model實(shí)現(xiàn)數(shù)據(jù)雙向綁定的文章就介紹到這了,更多相關(guān)V-model數(shù)據(jù)雙向綁定內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論