The parent component in Vue passes data to the child component through prop, and wants to pass the child component's data to the parent component, which can be bound by a custom event.
Each Vue instance implements the "event interface", which is:
1. Use $on (eventName) to monitor events
2. Trigger events using $emit (eventName)
The parent component can use v-on directly to listen for the events triggered by the subassembly, where the subassembly is used.
HTML code:
1 <DivID= "Counter-event-example">2 <P>{{Total}}</P>3 <Button-counterv-on:increment= "Incrementtotal"></Button-counter>4 <Button-counterv-on:increment= "Incrementtotal"></Button-counter>5 </Div>
CSS code:
1 vue.component (' Button-counter ',{2 Template:' <button v-on:click= ' increment ' >{{counter}}</button> ',3 data:function (){4 return {5 counter:06}7 },8 methods:{9 Increment:function () {Ten This.counter + = 1 One This . $emit (' increment ') A} - }, - }) the New Vue ({ - El:' #counter-event-example ', - data: { - total:0 +}, - methods:{ + Incrementtotal:function () { A This.total + = 1 at} - } - })
The Click event is bound to the function increment in the sub-component. Clicking on the sub-component's button will trigger the increment function located in the subassembly.
this
.$emit(
‘increment‘
)
This is the event that triggers the current instance. Additional parameters are passed to the listener callback.
The child component notifies the parent component by $emit when the increment function is called. In this way, the communication between parent and child components is formed.
In the normal component communication, the parent component is passed through the props parameter to the child component, and the child component passes to the parent component to use the custom event.
In this way, the parent and child components are decoupled, and the subcomponents receive the implementation inside the parent component
Understanding of v-on Binding custom events in vue2.0