//子组件
<template>
<div>
<input v-model="sea" @input="valChange(sea)" />
<input v-model="add" @input="valChange2(add)" />
</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" />
<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>
效果:
?
|