Vue3中組件的雙向綁定統(tǒng)一使用 v-model 進行處理,并且可以和多個數(shù)據(jù)進行綁定,例如 v-model:foo、v-model:bar。
v-model 等價于 :model-value="someValue"
和 @update:model-value="someValue = $event"
v-model:foo 等價于 :foo="someValue"
和 @update:foo="someValue = $event"
父子組件之間雙向綁定
<!-- 父組件 -->
<script setup>
import ChildModulefrom './ChildModule.vue'
import { ref } from 'vue'
const msg = ref('hello vue3!')
</script>
<template>
<ChildModule v-model="msg" />
</template>
<!-- 子組件 -->
<script setup>
defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])
</script>
<template>
<div @click="emit('update:modelValue', 'hi vue3!')">{{ modelValue }}</div>
</template>
子組件可以結(jié)合 input 使用:文章來源:http://www.zghlxwxcb.cn/news/detail-512776.html
<!-- 子組件 -->
<script setup>
defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])
</script>
<template>
<input :value="modelValue" @input="emit('update:modelValue', $event.target.value)" />
</template>
也可以結(jié)合 computed 一起使用:文章來源地址http://www.zghlxwxcb.cn/news/detail-512776.html
<!-- 子組件 -->
<script setup>
import { computed } from 'vue'
const props = defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])
const newValue = computed({
get() {
return props.modelValue
},
set(value) {
emit('update:modelValue', value)
}
})
</script>
<template>
<input v-model="newValue" />
</template>
到了這里,關(guān)于vue3組件之間雙向綁定的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!