vue3父子同信的双向数据实现3种方式

前言:

我们知道的是,父传子的通信,和子传父的通信,那如何实现父子相互通信的呢?

(vue3中)v-model 和modelValue结合使用,在vue2中使用的是.sync
  1. 第一种

在父组件的写法

<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>
  1. 第二种

另一种是在父组件中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>
  1. 第三种 使用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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值