Context
In Vue 2.0 the documentation and others clearly indicate that communication from parent to child happens via props.
Question
How does a parent tell its child an event has happened via props?
Should I just watch a prop called event? That doesn't feel right, nor do alternatives ($emit
/$on
is for child to parent, and a hub model is for distant elements).
Example
I have a parent container and it needs to tell its child container that it's okay to engage certain actions on an API. I need to be able to trigger functions.
Give the child component a
ref
and use$refs
to call a method on the child component directly.html:
javascript:
You can use
$emit
and$on
. Using @RoyJ code:html:
javascript:
Running example: https://jsfiddle.net/rjurado/m2spy60r/1/
A simple decoupled way to call methods on child components is by emitting a handler from the child and then invoking it from parent.
The parent keeps track of the child handler functions and calls whenever necessary.
I think we should to have a consideration about the necessity of parent to use the child’s methods.In fact,parents needn’t to concern the method of child,but can treat the child component as a FSA(finite state machine).Parents component to control the state of child component.So the solution to watch the status change or just use the compute function is enough
Did not like the event-bus approach using
$on
bindings in the child duringcreate
. Why? Subsequentcreate
calls (I'm usingvue-router
) bind the message handler more than once--leading to multiple responses per message.The orthodox solution of passing props down from parent to child and putting a property watcher in the child worked a little better. Only problem being that the child can only act on a value transition. Passing the same message multiple times needs some kind of bookkeeping to force a transition so the child can pick up the change.
I've found that if I wrap the message in an array, it will always trigger the child watcher--even if the value remains the same.
Parent:
Child:
HTML:
What you are describing is a change of state in the parent. You pass that to the child via a prop. As you suggested, you would
watch
that prop. When the child takes action, it notifies the parent via anemit
, and the parent might then change the state again.If you truly want to pass events to a child, you can do that by creating a bus (which is just a Vue instance) and passing it to the child as a prop.