Vue父子组件双向绑定传值的实现方法


从某方面讲,父组件传值给子组件进行接收,之后在子组件中更改是不允许的。你会发现vue也会直接报错,而在封装一些组件的时候,又希望做到数据的双向绑定,可以更好的控制与使用,在网上找到了两种方法,一种的话是使用 v-model 还有一种是 .sync
这里我推荐使用.sync

原因:v-mode只能进行单个双向绑定值而使用.sync可支持多个双向绑定值,当然,具体使用哪个可以参照自己的使用场景来区分

这里我就来写个通过.sync 实现父子数据双向绑定的例子

 

代码如下:

这是父组件

vi设计http://www.maiqicn.com 办公资源网站大全https://www.wode007.com

<template> <div class="home"> <!-- 此处只需在平时常用的单向传值上加上.sync修饰符 --> <HelloWorld :msg.sync="parentMsg" :msg2.sync="parentMsg2" /> </div> </template> <script> import HelloWorld from '@/components/HelloWorld.vue' export default { name: 'home', data(){ return{ parentMsg:'test', parentMsg2:'test2' } }, watch:{ // 监听数据的变化输出 newV 改变的值,oldV 改变之前的值 parentMsg(newV,oldV){ console.log(newV,oldV); }, parentMsg2(newV,oldV){ console.log(newV,oldV); } }, components: { HelloWorld } } </script> 

子组件

<template> <div> <h1>{{ msg }}</h1> <h1>{{ msg2 }}</h1> <button @click="fn()">点击</button> </div> </template> <script> export default{ props:{ msg:String, msg2:String }, methods:{ fn(){ let some = '张三'; let some2 = '李四'; // 将这个值通过 emit // update为固定字段,通过冒号连接双向绑定的msg,将some传递给父组件的v-model绑定的变量 this.$emit('update:msg',some); this.$emit('update:msg2',some2); } } } </script> 

此处需要注意,虽然加上 .sync 即可双向绑定,但是还是要依靠子组件 $emit 去触发 update:prop名 实现修改父组件的变量值实现双向数据流,如果直接对prop的属性直接赋值,依然会出现报错。

事实上, .sync 修饰符是一个简写,它做了一件事情

<template> <HelloWorld :msg.sync="parentMsg" :msg2.sync="parentMsg2" /> <!-- 等价于 --> <HelloWorld :msg="parentMsg" @updata:msg="parentMsg = $event"></HelloWorld> <!-- 这里的$event就是子组件$emit传递的参数 --> </template>


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM