Vue two-way binding between parent and child components
In Vue, the most commonly used two-way binding is v-model.
For example, you can do the following to have a two-way binding on a text input.
The value of userInput will be shown in the text input, and the user's input into the control will update the userInput.
Then how to write a two-way binding for my own component?
Here I want to implement a Setting component which contains a checkbox for a setting, say, "Mirror".
Don't directly mutate a prop
You can't do the following because mirror is passed in as a prop and you shouldn't mutate it.
Otherwise you'll get the following warning.
Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "mirror"
.sync Modifier
Then what's the right way to do it? You can get some idea by reading .sync modifier
In Vue, it's recommended to emit events in the pattern of update:myPropName.
this.$emit('update:title', newTitle)
Then the parent can listen to that event and update a local data property.
For convenience, they offer a shorthand for this pattern with the .sync modifier:
Example
Now back to our example. In the parent component we can simply add .sync modifier to the mirror binding.
And in the child component, instead of using v-model, we need to use two bindings -- one for reading value, another for writing value.
As for checkbox, reading the value is done with checked binding. And writing the value is done by the change event.
本文章由javascript技术分享原创和收集
发表评论 (审核通过后显示评论):