前言:
我们知道的是,父传子的通信,和子传父的通信,那如何实现父子相互通信的呢?
(vue3中)v-model 和modelValue结合使用,在vue2中使用的是.sync
- 第一种
在父组件的写法
<template>
<Son v-model="num" />
</template>
<script setup>
import Son from "./children.vue"
import {ref} form 'vue'
const num = ref(0)
</script>
子组件的写法
<template>
<div>{{modelValue}} </div>
<button @click="addNum">按钮</button>
</template>
<script setup>
const props =difineProps({
modelValue:Number
})
const emit = difineEmits(["update:modelValue"])
const addNum = ()=>{
emit("update:modelValue",modelValue++)
}
</script>
- 第二种
另一种是在父组件中v-model:XX,在子组件中用XX
在父组件的写法
<template>
<Son v-model:val="num" />
</template>
<script setup>
import Son from "./children.vue"
import {ref} form 'vue'
const num = ref(0)
</script>
子组件的写法
<template>
<div>{{num}} </div>
<button @click="addNum">按钮</button>
</template>
<script setup>
import {ref} form 'vue'
const props =difineProps({
val:Number
})
const num = ref(props.val)
const emit = difineEmits(["update:val"])
const addNum = ()=>{
emit("update:val",num++)
}
</script>
- 第三种 使用defineModel()
在父组件的写法
<template>
<Son v-model="num" />
</template>
<script setup>
import Son from "./children.vue"
import {ref} form 'vue'
const num = ref(0)
</script>
子组件的写法
<template>
<div>{{props }} </div>
<button @click="addNum">按钮</button>
</template>
<script setup>
const props =difineModel("num")
const addNum = ()=>{
props.value++
}
</script>