欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 游戏 > v-model+computed实现父子组件数据传递和同步

v-model+computed实现父子组件数据传递和同步

2025/3/20 8:57:27 来源:https://blog.csdn.net/weixin_42202992/article/details/146363802  浏览:    关键词:v-model+computed实现父子组件数据传递和同步

v-model+computed实现父子组件数据传递和同步

    • 1. 父组件
    • 2. 子组件
      • 说明
      • 总结

1. 父组件

<template><div><span>父子组件传值:{{countRef}}<my-counter v-model='count'></my-counter></span></div>
</template>
<script setup>
import { ref } from 'vue'
import MyCount from '@/views/passValue/MyCounter.vue'
const count = ref(0)
</script><style scoped></style>

2. 子组件

<template><div><input type="text" v-model="value"/></div>
</template>
<script setup>
import { computed } from 'vue'
const props = defineProps({count:{type:Number}
})
const emit = defineEmits(['update:modelValue'])
const value = computed(()=>{get(){return props.modelValue},set(val){emit("update:modelValue",val)}
})
</script><style scoped></style>

说明

  1. 父组件:
    在模板中,父组件使用 v-model 将 count传递给子组件。
    count是父组件的一个响应式数据,初始化为 “初始值”。
  2. 子组件:
    子组件通过 props 接收父组件传来的 modelValue。
    使用 computed 属性 modelValue来管理这个 modelValue。在 get 方法中,它返回接收到的值,而在 set 方法中,使用 $emit 报告父组件值的变化。
  3. 双向绑定:
    通过这种方式,父组件和子组件之间实现了双向绑定:当子组件的输入框内容改变时,父组件的 parentValue 会更新;当父组件的 parentValue 改变时,子组件的输入框也会自动显示新的值。

总结

使用 v-model 和 computed 可以有效地实现父子组件之间的数据传递和同步

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词