1、回忆下v-model在原生input元素上的用法:
<input v-model="text" />
等价于
<input
:value="text"
@input="text = $event.target.value"
/>
2、使用v-model在组件上实现双向绑定(通过计算属性实现)
父组件
<template>
<div>
<input type="text" v-model="data">
<Son v-model="data"></Son>
</div>
</template>
<script lang="ts" setup>
import Son from './Son.vue';
import { ref } from 'vue'
const data = ref('joke')
子组件
<template>
<div>
<input type="text" v-model="inputRef.val">
</div>
</template>
<script lang="ts" setup>
import { reactive, computed } from 'vue'
//父组件给子组件传值时,没用使用名字而是使用v-model,则子组件接收时默认名字为modelValue
const props = defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])
const inputRef = reactive({
val: computed({
get:() => props.modelValue || '',
set: val => {
emit("update:modelValue", val)
}
})
})
</script>
3、使用input事件的方式:
引用文章: https://blog.csdn.net/l2345432l/article/details/126017725
官方文档:https://cn.vuejs.org/guide/components/v-model.html#v-model-arguments