Custom events are required for Vue child components to pass values to parent components
Process:
1. The child component creates and listens for custom events,
2. Execute the emit function inside the event function and emit the value to the parent component
3. The parent component listens for the event name defined by emit on the child component and binds its own functions, receiving the arguments passed by the child component in the arguments of the function.
Implementation code:
<! DOCTYPE HTML > < HTML > <head> <meta charset=" UTF-8 "> <title> <meta name="viewport" The content = "width = device - width, initial - scale = 1.0, user - scalable = no, minimum - scale = 1.0, Maximum - scale = 1.0 "/ > < script SRC =" https://cdn.staticfile.org/vue/2.2.2/vue.min.js "> < / script > < / head > < body > < div id="app"> <div id="counter-event-example"> <p>{{ total }}</p> <! -- Two subcomponents are used here, because the subcomponent's data is a function, so their values do not affect each other --> <! The parent uses V-on directly where the child component is used to listen for events triggered by the child component. --> <button-counter v-bind:idx="1" v-on:increment="appAddCounter"></button-counter> <button-counter v-bind:idx="2" v-on:increment="appAddCounter"></button-counter> </div> </div> <script> Vue.component('button-counter', { //1. Listen for the event template using $on(eventName) : '< button v - on: click = "addCounter" > the first sub components: {{independence idx}} {{counter}} < / button >', props: [' independence idx], data: Function () {return {counter: 0}}, methods: {addCounter: function() {this.counter += 1; Var STR =' I am the first '+this.idx+' child, my value is: '+this.counter; $emit('increment', STR) $emit('increment', STR); $emit('increment', STR); $emit('increment', STR); } }, }) new Vue({ el: '#counter-event-example', data: { total: 0 }, methods: { appAddCounter: Function (e) {console.log(e) this.total += 1}}}) </script> </body> </ HTML >Copy the code
The second method:
In the parent component, pass the name of the method to be fired to the onOK property. In the child component, check whether onOK exists. If so, execute the method directly.
Effect: