vue 中父子组件传值的问题

1.父组件可以通过props向子组件传递参数,并监听子组件触发出来的方法;

props:['arg1','arg2']


2.子组件可以用 $emit 方法触发父组件的自定义事件。

vm.$emit( event ,arg);


### Vue2父子组件之间的方法 #### 父组件向子组件递数据 在 Vue2 中,父组件可以通过 `props` 向子组件递数据。这种方式遵循单向数据流的原则,即父组件的数据流向子组件,而子组件不能直接修改这些数据。 ```html <!-- Father.vue --> <template> <div> <son :num="fatherNum"></son> </div> </template> <script> import Son from './Son.vue'; export default { components: { Son }, data() { return { fatherNum: 100, }; } }; </script> ``` ```html <!-- Son.vue --> <template> <div> {{ num }} </div> </template> <script> export default { props: ['num'] }; </script> ``` 当父组件中的 `fatherNum` 发生变化时,子组件会自动更新接收到的 `num` [^1]。 #### 子组件向父组件递事件 为了实现从子组件到父组件的数据流动,可以使用自定义事件。子组件触发一个事件,父组件监听这个事件并作出相应处理。 ```html <!-- Son.vue --> <template> <button @click="updateParent">Update Parent Value</button> </template> <script> export default { methods: { updateParent() { this.$emit('update:num', newValue); // 自定义事件名 'update:num' } } }; </script> ``` ```html <!-- Father.vue --> <template> <div> <son :num.sync="fatherNum"></son> <!-- 使用 .sync 修饰符简化写法 --> </div> </template> <script> export default { data() { return { fatherNum: 100, }; } }; </script> ``` 这里展示了两种方式来同步父组件的状态: - **显式绑定**:通过 `@input` 或者其他名称的事件手动绑定。 - **`.sync` 语法糖**:更简洁的方式,在父组件中使用 `.sync` 修饰符。 对于复杂场景下的双向绑定需求,还可以考虑使用 `v-model` 来代替 `.sync` 和 `$emit` 的组合。 ```html <!-- Father.vue --> <template> <div> <son v-model="fatherNum"></son> </div> </template> <script> export default { data() { return { fatherNum: 100, }; } }; </script> ``` ```html <!-- Son.vue --> <template> <button @click="$emit('input', newValue)">Change Value</button> </template> <script> export default {}; </script> ``` 这种模式下,默认情况下输入框或其他表单元素可以直接利用 `v-model` 实现与父级状态的联动。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值