//子组件
<template>
<div>
<input v-model="sea" @input="valChange(sea)" />
<input v-model="add" @input="valChange2(add)" />
<!-- @input输入框发生变化后触发(将v-model传给父组件) -->
</div>
</template>
<script lang="ts">
import { defineComponent, ref, watch } from 'vue'
export default defineComponent({
name: 'ChildComp',
props: {
modelValue: { // 父组件 v-model 没有指定参数名,则默认是 modelValue
type: String,
default: ''
},
address: {
type: String,
default: ''
}
},
setup (props, { emit }) {
// input初始化
const sea = ref(props.modelValue)
const add = ref(props.address)
// 因为props.modelValue、props.address是非引用类型,改变时,需要监听,对响应式数据重新赋值
watch(() => props.modelValue, () => { sea.value = props.modelValue })
watch(() => props.address, () => { add.value = props.address })
// 数据双向绑定
function valChange (e: string) {
emit('update:modelValue', e)
}
// 数据双向绑定
function valChange2 (e: string) {
emit('update:address', e)
}
return {
sea,
add,
valChange,
valChange2
}
}
})
</script>
//父组件
<template>
<div>
<ChildComp v-model="search" v-model:address="addr" />
<!-- search接收的就是emit("update:modelValue")的参数 -->
<h1>{{ search }}</h1>
<h1>{{ addr }}</h1>
</div>
</template>
<script>
import { defineComponent, ref } from 'vue'
import ChildComp from '../components/ChildComp'
export default defineComponent({
name: 'Index',
components: {
ChildComp
},
setup () {
const search = ref('')
const addr = ref('')
return {
search,
addr
}
}
})
</script>