1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>vue的自定义事件</title> 6 </head> 7 <body> 8 <div id="app"> 9 <my-btn @total="allcounter"></my-btn> 10 <my-btn @total="allcounter"></my-btn> 11 <my-btn @total="allcounter"></my-btn> 12 13 <p>所以按钮一共点击了{{totalCounter}}多少次</p> 14 </div> 15 16 <template id="my_btn"> 17 <button @click="total()">点击了{{counter}}次</button> 18 </template> 19 20 </body> 21 <script src="./vue.js"></script> 22 <script> 23 Vue.component('my-btn',{ 24 template:'#my_btn', 25 data(){ 26 return { 27 counter:0 28 } 29 }, 30 methods:{ 31 total(){ 32 this.counter++ 33 // 通知外界我调用了这个方法 34 this.$emit('total') 35 36 } 37 } 38 }) 39 new Vue({ 40 el:'#app', 41 data:{ 42 totalCounter:0, 43 }, 44 methods: { 45 allcounter(){ 46 this.totalCounter += 1 47 48 } 49 } 50 }) 51 </script> 52 </html>
效果图