//创建属于自己的vue组件库 (function(Vue, undefined) { Vue.component("my-component", { template: '<div @click="alertName">{{message.name}}<button @click="alertMessage">{{message.age}}</button></div>',//模板最外层必须只有一个标签包裹,不能同时存在两个 props: ['message'], data: function() { return { } }, methods: { alertName() { this.$emit('alerta')//事件名称必须小写,不然无效(此处浪费了我好长时间) }, alertMessage(){ this.$emit('alertmessage',this.message.name) } } }) }(Vue))
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script type="text/javascript" src="vue.js"></script> <script type="text/javascript" src="iview.js"></script> </head> <body> <div id="example"> <my-component :message="great" @alerta="alet" @alertmessage='alertb'></my-component> </div> <script type="text/javascript"> var vue=new Vue({ el: '#example', data:{ great:{ name:'wanglu', age:12 } }, methods:{ alet(){ this.great={name:'liuyu',age:13}; }, alertb(name){ alert(name); } } }) </script> </body> </html>