Vue 温故而知新 props如何双向属性绑定

传送门:https://vuejs.org/v2/guide/components-custom-events.html#sync-Modifier

https://segmentfault.com/q/1010000012055834/a-1020000012055960

1、最单纯的做法:事件回调

// 父组件
<msgbox :god='value' @shift="fuck"></msgbox>
fuck (data) { this.value = fuck } // 子组件 <button @click='go'></button>
go () { this.$emit('shift', '你要更新的值'); }

其实父组件如果只是赋值的话,可以写的更单纯一点。可以省略函数的定义和使用。(推荐)

// 父组件
<msgbox :god='value' @shift="value = $event"></msgbox>

// 子组件
<button @click='go'></button>
go () { this.$emit('shift', '你要更新的值'); }

2、官方推荐的做法: @update 

同1,我是看不出区别,如果是我,我建议使用1,反而可读性更强。

// 父组件
<msgbox :god='value' @update:fuck="fuck = $event"></msgbox>

// 子组件
<button @click='go'></button>
go () { this.$emit('update:fuck', '你要修改的值') }

3、我强烈推荐的做法:v-bind.sync

// 父组件,可以省略 @update 或者 @event
<msgbox :god.sync='value'></msgbox>

// 子组件
<button @click='go'></button>
go () { this.$emit('update:value', '你要修改的值') }

猜你喜欢

转载自www.cnblogs.com/CyLee/p/9721285.html