1.双向绑定传递基本数据类型
父组件
<template>
<div>
<test v-model="searchText"/>
<p>父组件值:{{ searchText }}</p>
</div>
</template>
<script setup lang='ts'>
import { ref } from 'vue'
import test from "@/components/test.vue";
const searchText=ref(0)
</script>
子组件(写法一)
<template>
<div>
<input type="text" :value="modelValue" @input="emit('update:modelValue',$event.target.value)">
</div>
</template>
<script setup lang='ts'>
const props=defineProps(
{
modelValue:{
type:Number,
require:true
}
}
)
const emit=defineEmits(['update:modelValue'])
</script>
子组件(写法二 绑定到计算属性上)
<template>
<div>
<input type="text" v-model="hhh">
</div>
</template>
<script setup lang='ts'>
import { computed } from "vue";
const props=defineProps(
{
modelValue:{
type:Number,
required:true
}
}
)
const emit=defineEmits(['update:modelValue'])
const hhh=computed({
get(){
return props.modelValue
},
set(value){
emit('update:modelValue',value)
}
})
</script>
2.双向绑定对象
父组件
<template>
<div>
<test v-model="obj"/>
<p>父组件值:{{ obj.name }}</p>
</div>
</template>
<script setup lang='ts'>
import { ref } from 'vue'
import test from "@/components/test.vue";
const obj=ref({
name:"小明",
age:28
})
</script>
子组件
<template>
<div>
<input type="text" v-model="modelValue.name">
</div>
</template>
<script setup lang='ts'>
const props=defineProps(
{
modelValue:{
type:Object,
required:true
}
}
)
const emit=defineEmits(['update:modelValue'])
</script>