注意:defineModel() 需要在vue3.4及以上版本才可使用
这个宏可以用来声明一个双向绑定 prop,通过父组件的 v-model 来使用
1. defineModel 的基本使用
1.1 父组件
<template>
<div class="pl-[4rem]">
<div>{{obj.age}}</div>
<div>{{obj.name}}</div>
</div>
<div class="pl-[4rem]">
# 使用v-model直接进行传值
<Child v-model="obj"></Child>
</div>
</template>
<script setup lang="ts">
import Child from './child.vue';
let obj = ref({
age : 12,
name: '张三'
});
</script>
1.2 子组件
<template>
<div>子组件</div>
<div>
# 在组件上面直接使用改变父组件传递过来的值
<input v-model="obj.name" type="text" placeholder="请输入姓名" />
<input v-model="obj.age" type="text" placeholder="请输入年龄" />
</div>
</template>
<script setup lang="ts">
# 子组件使用defineModel接收
let obj:any = defineModel();
</script>
2. defineModel 传递多个v-model
2.1 父组件---- (给v-model命名 子组件就能区分)
<template>
<div class="pl-[4rem]">
<div>age:{{obj.age}}</div>
<div>name:{{obj.name}}</div>
<div>title:{{obj2.title}}</div>
<div>number:{{number}}</div>
</div>
<div class="pl-[4rem]">
<Child v-model="obj" v-model:obj2="obj2" v-model:number="number"></Child>
</div>
</template>
<script setup lang="ts">
import Child from './child.vue';
let obj = ref({
age : 12,
name: '张三'
});
let obj2 = ref({
title : '我是父组件的标题'
})
let number = ref(10);
</script>
2.2 子组件
<template>
<div>子组件</div>
<div>
<input v-model="obj.name" type="text" placeholder="请输入姓名" />
<input v-model="obj.age" type="text" placeholder="请输入年龄" />
<input v-model="obj2.title" type="text" placeholder="标题" />
<input v-model="number" type="text" placeholder="number" />
</div>
</template>
<script setup lang="ts">
let obj:any = defineModel();
let obj2:any = defineModel('obj2');
let number = defineModel('number');
</script>
3. defineModel 设置额外参数如类型、默认值
let obj:any = defineModel('obj',{default: '1', type: Object as any, required: true});
4. defineModel 对接收的值做一些操作
4.1 父组件
<template>
<div class="pl-[4rem]">
<div>age:{{obj}}</div>
</div>
<div class="pl-[4rem]">
<Child v-model:obj="obj"></Child>
</div>
</template>
<script setup lang="ts">
import Child from './child.vue';
let obj = ref(10);
</script>
4.2 子组件
<template>
<div>子组件</div>
<div>
<input v-model="obj" type="text" placeholder="请输入姓名" />
</div>
</template>
<script setup lang="ts">
let obj: any = defineModel("obj", {
type: Number,
default: 0,
get(val) {
console.log("AAA1", val);
return val;
},
set(val) {
console.log("AAA2", val);
return val + '我';
},
});
</script>