Vue3 has made some changes in the way of bidirectional data binding for parent and child components, and also supports multiple data bidirectional binding.The official API
- Bidirectional binding of single data
- Child components
<template>
<div>
<input v-model="sea" @input="valChange(sea)" />
</div>
</template>
<script lang="ts">
import { defineComponent, ref, watch } from 'vue'
export default defineComponent({
name: 'ChildComp'.props: {
modelValue: { // The parent component v-model does not specify a parameter name, so the default is modelValue
type: String.default: ' '
}
},
setup (props, { emit }) {
// Input is initialized
const sea = ref(props.modelValue)
// If the data from the parent component is retrieved asynchronously, you need to listen
watch(() = > props.modelValue, () = > { sea.value = props.modelValue })
// Two-way data binding
function valChange (e: string) {
emit('update:modelValue', e)
}
return {
sea,
valChange
}
}
})
</script>
Copy the code
- The parent component
<template>
<div>
<! -- v-model specifies no parameter name, the child component default parameter name is modelValue -->
<ChildComp v-model="search" />
<h1>{{ search }}</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(' ')
return {
search
}
}
})
</script>
Copy the code
- Multiple data bidirectional binding
- Child components
<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: { // The parent component v-model does not specify a parameter name, so the default is modelValue
type: String.default: ' '
},
address: {
type: String.default: ' '
}
},
setup (props, { emit }) {
// Input is initialized
const sea = ref(props.modelValue)
const add = ref(props.address)
// If the data from the parent component is retrieved asynchronously, you need to listen
watch(() = > props.modelValue, () = > { sea.value = props.modelValue })
watch(() = > props.address, () = > { add.value = props.address })
// Two-way data binding
function valChange (e: string) {
emit('update:modelValue', e)
}
// Two-way data binding
function valChange2 (e: string) {
emit('update:address', e)
}
return {
sea,
add,
valChange,
valChange2
}
}
})
</script>
Copy the code
- The parent component
<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>
Copy the code