I'm starting to play with vuejs (2.0).
I built a simple page with one component in it.
The page has one Vue instance with data.
On that page I registered and added the component to html.
The component has one input[type=text]
. I want that value to reflect on the parent (main Vue instance).
How do I correctly update the component's parent data? Passing a bound prop from the parent is not good and throws some warnings to the console. They have something in their doc but it is not working.
From the documentation:
How to pass props
Following is the code to pass props to a child element:
How to emit event
HTML:
JS:
It is also possible to pass props as Object or Array. In this case data will be two-way binded:
(This is noted at the end of topic: https://vuejs.org/v2/guide/components.html#One-Way-Data-Flow )
In child component:
this.$emit('eventname', this.variable)
In parent component:
I agree with the event emitting and v-model answers for those above. However, I thought I would post what I found about components with multiple form elements that want to emit back to their parent since this seems one of the first articles returned by google.
I know the question specifies a single input, but this seemed the closest match and might save people some time with similar vue components. Also, no one has mentioned the
.sync
modifier yet.As far as I know, the
v-model
solution is only suited to one input returning to their parent. I took a bit of time looking for it but Vue (2.3.0) documentation does show how to sync multiple props sent into the component back to the parent (via emit of course).It is appropriately called the
.sync
modifier.Here is what the documentation says:
You can also sync multiple at a time by sending through an object. Check out the documentation here
Two-way binding has been deprecated in Vue 2.0 in favor of using a more event-driven architecture. In general, a child should not mutate its props. Rather, it should
$emit
events and let the parent respond to those events.In your specific case, you could use a custom component with
v-model
. This is a special syntax which allows for something close to two-way binding, but is actually a shorthand for the event-driven architecture described above. You can read about it here -> https://vuejs.org/v2/guide/components.html#Form-Input-Components-using-Custom-Events.Here's a simple example:
The docs state that
is equivalent to
That is why the prop on the child needs to be named value, and why the child needs to $emit an event named
input
.