vue3中实现v-model的原理于vue2类似,不同之处在于vue2中绑定的是属性是value
,对外发送的事件的input
,而在vue3中则改为默认绑定modelValue
,默认对外发送的事件为update:modelValue
<template>
<!-- 组件默认的v-model -->
<input type="text" :value="modelValue" @input="handleInput" />
</template>
<script setup>
import { defineProps, defineEmits } from "vue"
let props = defineProps({
modelValue: Number,
})
let emit = defineEmits(['update:modelValue'])
function handleInput(value) {
emit('update:modelValue',value.target.value)
}
</script>
<template>
<myInput v-model="num" />
{{num}}
</template>
<script setup>
import { ref } from "vue"
import myInput from "./my_input.vue"
let num = ref(10)
</script>
在vue3中v-model绑定的实现不再局限于value
,而是可以通过v-model:xxx
的方式进行之定义,在组件内部将事件update:modelValue
改为update:xxx
即可
<template>
<!-- 组件默认的v-model -->
<input type="text" :value="title" @input="handleInput" />
</template>
<script setup>
import { defineProps, defineEmits } from "vue"
let props = defineProps({
title: Number,
})
let emit = defineEmits(['update:title'])
function handleInput(value) {
emit('update:title',value.target.value)
}
</script>
<template>
<myInput v-model:title="title" />
{{title}}
</template>
<script setup>
import { ref } from "vue"
import myInput from "./my_input.vue"
let title= ref("标题")
</script>