Vue Sync

Posted on  by admin

官方推荐使用一种update:my-prop-name 的模式来替代事件触发,目的是为了优雅而不粗鲁的实现父子组件间的双向绑定!先来完成一个小功能:通过父组件按钮将子组件显示出来,如图:. 至此终于涉及到了sync了。以上代码 :isShow.sync="isShow"其实是 @update:isShow="bol=>isShow=bol"语法糖。是其一种简写形式。附上完整代码。父组件:.

Vue中的 props 是单向向下绑定的即:每次父组件更新时,子组件中的所有 props 都会刷新为最新的值。但是如果在子组件中修改 props ,Vue会向你发出一个警告。(无法通过修改子组件的props来更改父组件。). Vue帮我们做了一个修饰符,简化我们声明监听事件的写法,即.sync 修饰符。. 所以尤雨溪发明了.sync ,示例. 从 2.3.0 Vue重新引入了 .sync 修饰符,但是这次它只是作为一个编译时的语法糖存在。它会被扩展为一个自动更新父组件属性的 v-on 监听器。.

当子组件需要更新 foo 的值时,它需要显式地触发一个更新事件:. 今天学习了 Vue 的模板、指令和修饰符,对于 .sync 这个修饰符不是能特别好地理解,所以写一篇博客来整理下思路。. 因为这种情况用到的很多,所以Vue用.sync修饰符来给这个模式提供了一个缩写。我们把这行简化一下变成就可以了,与上面一行完全等价。.

这就是 Vue 的 .sync 修饰符的作用。. Most Vue.js newbies might have encountered this one particular warning at-least once in your console.

It occurs when you try to mutate a parent component property in a child component. properties in components follow a one-way data flow. i.e., when the parent property updates, it will flow down to the child, but not the other way around.

To overcome, vue provides $emit event. All we need to do is listen for $emit event from child with a v-on directive on the parent component and update the properties with a event listener function. In the example below, we pass count property from parent to child component.

On increment action we emit updatedCount event from the child and in the parent we added a listener setUpdatedCount function to update the count property.

This solves the issue and works perfectly.

But writing a listener function to update just a property seems too many lines of code. To simply, modify the below lines.

Looks good, right? To improve further, version 2.3.0 onwards, Vue.js provides a new modifier sync. sync modifier comes with even more flexibility for updating multiple props in objects.

Checkout the docs here. Note of caution:. There are also certain limitations using sync with objects and expressions. The docs page have those limitations detailed. Francium Tech is a technology company laser focussed on delivering top quality software of scale at extreme speeds. Numbers and Size of the data don’t scare us.

If you have any requirements or want a free health check of your systems or architecture, feel free to shoot an email to [email protected], we will get in touch with you!

Modified4 years, 9 months ago. In my vue application I've got lots and lots of input fields (example):.

So I would like to wrap this in a input component. But since vue 1 the .sync method is gone so how would I do this?