在vue3中我们可以使用 v-model 格式来实现父子组件之间数据的双向同步,我们只需要按照以下的格式即可实现
父组件
在子组件中 使用 v-model:xxx="xxxx" 格式
<template>
<div class="app-container">
<h1>APP 根组件</h1>
<p>count: {{count}}</p>
<button @click="addCount">count +1</button>
<hr>
<Son v-model:count="count"></Son>
</div>
</template>
<script>
import Son from './son.vue'
import { reactive, toRefs, ref, onMounted, onUnmounted } from 'vue'
export default {
name: 'App',
components: {
Son
},
setup() {
const count = ref(18)
const addCount = () => {
count.value++
}
return { count, addCount }
}
}
</script>
<style>
</style>
子组件
子组件使用 props 来接收父组件传递过来的数据 count 。
子组件使用 emits 来定义自定义事件 格式: ['update:xxx']
子组件 setup 函数 使用形参 setup(props,{emits}) {}
<template>
<h1>Son 组件</h1>
<p>父组件接收的count: {{count}}</p>
<button @click="changeCount">改变传过来的count </button>
</template>
<script>
export default {
name: 'Son',
emits: ['update:count'],
props: {
count: {
type: Number,
default: 0
}
},
setup(props, { emit }) {
console.log(props.count)
const changeCount = () => {
const pp = props.count + 1
emit('update:count', pp)
}
return { changeCount }
}
}
</script>
<style>
</style>