vue3实现父子组件的双向绑定
·
背景
我们在做日常的业务需求时,必然会涉及到大量的父子组件之间的数据传递,这样就会涉及到使用v-model去往子组件里传数据,达到双向绑定的效果:
以下是我整理了两种实现父子组件双向绑定的方法。
方法一:通过watch监听
父组件代码如下:
<template>
<div>
{{ value }}
<Child v-model:value="value"/>
</div>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import Child from './Child.vue'
const value = ref<string>()
</script>
子组件代码:
<template>
<div>
<span>我是子组件</span>
<Input v-model:value="inputValue" @change="handleChange"/>
</div>
</template>
<script setup lang="ts">
import { watch, ref } from 'vue'
import { Input } from 'ant-design-vue'
const props = defineProps<{
value: string
}>()
const inputValue = ref<string>('')
const emit = defineEmits<{
(e: 'update:value', v: string): void
}>()
watch(() => props.value, () => {
inputValue.value = props.value
})
const handleChange = (e: any) => {
emit('update:value', e.target.value)
}
</script>
方法二:通过computed属性
父组件代码:
<template>
<div>
{{ value }}
<Child v-model:value="value"/>
</div>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import Child from './Child.vue'
const value = ref<string>()
</script>
子组件代码:
<template>
<div>
<span>我是子组件</span>
<Input v-model:value="inputValue"/>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { Input } from 'ant-design-vue'
const props = defineProps<{
value: string
}>()
const emit = defineEmits<{
(e: 'update:value', v: string): void
}>()
const inputValue = computed({
get: () => props.value,
set: (val) => {
emit('update:value', val)
}
})
</script>
题外话
本人空闲时间做了一个计算房贷的微信小程序,有需求,有兴趣的可以扫码看看

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)