Note: global or local register called subassembly components, wherein the component name declared (child follows the demo) is a custom component
Demo1- directly to the parent component to add event listeners
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 <script src="../../vue.js"></script> 7 </head> 8 <body> 9 <div id="root" @click="handleClick"> 10 Child 11 </div> 12 <script> 13 Vue.component('child', { 14 template: '<div>Child</div>' 15 }) 16 17 var vm = new Vue({ 18 el: '#root', 19 methods: { 20 handleClick: function() { 21 alert(1); 22 } 23 } 24 }) 25 </script> 26 </body> 27 </html>
Demo2- use $ emit () release event broadcast, then the parent component sub-assemblies can listen to events outside trigger, and perform the appropriate method to
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 <script src="../../vue.js"></script> 7 </head> 8 <body> 9 <div id="root"> 10 <child @click="handleClick"></child> 11 </div> 12 <script> 13 Vue.component('child', { 14 template: '<div @click="handleChild">Child</div>', 15 methods: { 16 handleChild: function() { 17 this.$emit('click'); 18 } 19 } 20 }) 21 22 var vm = new Vue({ 23 el: '#root', 24 methods: { 25 handleClick: function() { 26 alert(1); 27 } 28 } 29 }) 30 </script> 31 </body> 32 </html>
Note: However, this approach is to bind components custom events, rather than binding to the native event and triggered two events, more trouble, this time method requires the use of demo3
Demo3- event modifier native can be used directly
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 <script src="../../vue.js"></script> 7 </head> 8 <body> 9 <div id="root"> 10 <child @click.native="handleClick"></child> 11 </div> 12 <script> 13 Vue.component('child', { 14 template: '<div>Child</div>' 15 }) 16 17 var vm = new Vue({ 18 el: '#root', 19 methods: { 20 handleClick: function() { 21 alert(1); 22 } 23 } 24 }) 25 </script> 26 </body> 27 </html>
Excerpt: https: //www.cnblogs.com/tu-0718/p/11196009.html