vue实现父子组件的双向数据绑定
- vue组件之间可以通过props实现父组件 -> 子组件的传值方式。
- 子组件可以通过$emit 回调函数传给父组件值。
父子组件可以通过sync修饰符来达到双向绑定的效果。
content.vue
<template> <Container type="card-full"> <template slot="header"> 用户中心 </template> doing... </Container> </template> <template> <div> <h1>父组件{{value1}}</h1> 我是父组件的input<input v-model="value1"/> <Child :name.sync="value1" /> <Child :name.once="value1" /> <Child :name="value1" /> <Child2 :name='value1'/> </div> <!-- <Child v/> --> </template> <script> import Child from './Child.vue' import Child2 from './Child2.vue' export default { data(){ return { value1:"hello" } }, components:{Child,Child2}, } </script>
child.vue
<template> <div>子组件<input v-model='curName'></div> </template> <script> export default { name: "box", data() { return { curName: this.name }; }, props: ["name"], watch: { name: function(newVal, oldVal) { this.curName = newVal; }, curName: function(newVal, oldVal) { this.$emit("update:name", newVal); } } }; </script>
通过上面方式实现双向数据绑定会产生一下现象
子组件更新,父组件也更新,同时会影响其他组件的数据。状态变的不可控。

浙公网安备 33010602011771号