<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <script src="js/Vue.js"></script> <div id="app"> <incbutton></incbutton> </div> <div id="app1"> <component-a></component-a> <timesa></timesa> </div> <script type="text/javascript"> Vue.component('timesa',{ template:`<h2>你好,当前时间是:{{time1}}</h2>`, data(){ return { time1: new Date().toLocaleTimeString(), _ti:null } }, methods:{ updatetime(){ this.time1=new Date().toLocaleTimeString() } }, created(){ this._ti=setInterval(this.updatetime,1000); }, breforeDestory(){
//释放 this._ti.claer(); } }) Vue.component('component-a',{ template:`<h1>你好,现在时间是:{{date}}</h1>`, data(){ return { date:new Date().toLocaleTimeString(), timer:null } }, methods:{ updateTime(){ this.date=new Date().toLocaleTimeString(); } }, created(){ this.timer=setInterval(this.updateTime,1000); }, beforeDestory(){
//释放 this.timer.claey(); } }) new Vue({el:'#app1'})
//定义组件 var my ={ template:`<button @click='incr' @mouseover='del()'>你已经点击了{{count}}</button>`, data(){ return{ count :0 } }, methods:{ incr(){ this.count = this.count +1; }, del(){ this.count=this.count-1; } } }
//注册组件名 Vue.component('incbutton',my); //使用组件 var vm=new Vue({ el:"#app" }); </script> </body> </html>
运行效果: