Preface
The first time I met .sync
modifier, I didn’t know it very well. So, I seldom use that. Today, I am going to get it.
Main
In the past, I use “two-way binding” like this:
<div class="app" id="app"> |
let app = new Vue({ |
It was easy to understand except a little inconvenient. I need to listen and handle event in child and parent component. Also
true two-way binding can create maintenance issues, because child components can mutate the parent without the source of that mutation being obvious in both the parent and the child.
So, Vue recommends emitting events in the pattern of update:myPropName
. For example:
<div class="app" id="app"> |
let app = new Vue({ |
See? In this case, we don’t have to add event callback in parent component because vue have done that. And this is the principle of .sync
. For convenience, Vue offers a shorthand for this pattern with the .sync
modifier which would make the code above like:
<div class="app" id="app"> |
let app = new Vue({ |
Also,
The .sync modifier can also be used with v-bind when using an object to set multiple props at once:
<text-document v-bind.sync="doc"></text-document> |
This passes each property in the doc
object (e.g. title
) as an individual prop, then adds v-on
update listeners for each one.
For more information, go Vue.js