Vue中如何实现双向绑定
1.Vue中如何实现双向绑定
双向绑定的需要
在有些情况下,我们可能需要对一个 prop 进行“双向绑定”。不幸的是,真正的双向绑定会带来维护上的问题,因为子组件可以变更父组件,且在父组件和子组件两侧都没有明显的变更来源。
vue2中双向绑定的实现(2.3.0+)
在vue2中实现双向绑定,主要是在在父组件中使用 :属性名.sync修饰符和在子组件中this.emit('update:属性名',属性值)方式去实现
子组件
<template> <div class="hello"> <div> {{ num }} </div> <button @click="addNum"></button> </div> </template> <script> export default { name: "TwoWayBinding", props: { num: Number, }, methods: { addNum() { this.$emit("update:num", this.num + 1); }, }, }; </script>
父页面
<template> <div id="app"> <TwoWayBinding :num.sync="num" /> </div> </template> <script> import TwoWayBinding from "./components/TwoWayBinding.vue"; export default { name: "App", components: { TwoWayBinding, }, data() { return { num: 4, }; }, mounted() {}, }; </script>
vue3.2中双向绑定的实现
在vue3中实现双向绑定,主要是在在父组件中使用v-model:属性名和在子组件中emit('update:属性名',属性值)的方式去实现
子组件
<template> <div>{{num}}</div> <button @click="addNum">加1</button> </template> <script setup> import {defineProps,defineEmits} from 'vue' const props = defineProps({ num:Number }) const emit = defineEmits('update:num') const addNum = () =>{ emit('update:num',props.num+1) } </script>
父页面
<template> <div id="app"> <two-way-binding-vue v-model:num="num"></two-way-binding-vue> </div> </template> <script setup> import { ref } from 'vue'; import TwoWayBindingVue from './components/TwoWayBinding.vue'; const num = ref(4) </script>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?