实现自定义组件<User v-model="userInfo" v-model:gender="gender"></User>
User组件中更改数据可以同步更改父组件中的数据:
1 父组件:
<User v-model="userInfo" v-model:gender="gender"></User>
<p style="font-size: 10px;">{{userInfo.name}} || {{userInfo.password}} </p>
<p style="font-size: 10px;">{{gender}}</p>
const userInfo=ref({
name:"第一",
password:"pass"
})
const gender=ref("male")
2 子组件:
<template>
<div>
<p>
用户名111: <input type="text" v-model="user.name">
</p>
<p>
密码222:<input type="text" v-model="user.password">
</p>
<p>
gender:<input type="text" v-model="genderVal">
</p>
<p>Name: {{ user.name }}</p>
<p>Password: {{ user.password }}</p>
<p>gender: {{ genderVal }}</p>
</div>
</template>
<script setup lang='ts'>
import { ref, reactive, watch } from 'vue'
const user=ref({
name:"",
password:""
})
const genderVal=ref("")
const props=defineProps({
modelValue:{
//v-model默认传给子组件的key是modelValue,
//其他则在父组件需要通过v-model:gender="gender"分别对应
type:Object,
default:()=>{}
},
gender: { // 对应v-model:gender="gender"中冒号后面的key
type: String,
default: "male",
},
})
const emits=defineEmits(['update:modelValue',"update:gender"])
//每个v-model定义的值对应的事件分别对应update:modelValue',"update:gender"
watch(user,(n,o)=>{
console.log("user.value",user.value)
emits("update:modelValue",user.value)
},{deep:true})
watch(()=>genderVal.value,(n,o)=>{
console.log("props.value--",n)
emits("update:gender",n)
})
</script>
<style lang='scss' scoped>
</style>