自定义Vue组件的三步骤
1、创建组件
2、注册组件
3、使用组件
创建组件
//创建组件 var myclock = { data(){ return { clock: new Date().toLocaleString(), _timer:null } }, methods:{ updateTime(){ this.clock = new Data().toLocaleString(); } }, created(){ this._timer = setInterval(this.update,1000); }, beforeDestroy(){ this._timer.cancel(); }, template:`<div>{{clock}}</div>` };
注册组件
//注册组件,名为myclock
Vue.component("myclock",myclock);
var vm = new Vue({
el: "#app"
});
使用组件
<div id="app"> <h3>组件示例</h3> <div> <!-- 使用组件 --> <myclock></myclock> </div> </div>
运行结果
一些简单例子代码
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <script src="js/incbutton.js"></script> <script src="js/vue.js"></script> <div id="app"> <h3>组件示例</h3> <div> <!-- 使用组件 --> <incbutton></incbutton> <br /> <myclick></myclick> <br/> <myclock></myclock> </div> </div> <script> //定义组件 var mytemplate1 = { template: `<div> <button @click='dianzan' v-bind:style="{color:colors}" >点赞</button> <button @click='guanzhu' v-bind:style="{color:colors1}" >关注</button> <myclock></myclock> </div>`, data() { return { isNumber: 1, isCount: 1, colors:'', colors1:'' } }, methods: { dianzan(){ this.isNumber = this.isNumber +1 ; if(this.isNumber % 2 == 0 ){ this.colors ="red"; }else{ this.colors ="black"; } }, guanzhu(){ this.isCount = this.isCount +1 ; if(this.isCount % 2 == 0 ){ this.colors1 ="red"; }else{ this.colors1 ="black"; } } } }; //注册组件 var myclock = { data(){ return { clock: new Date().toLocaleString(), _timer:null } }, methods:{ updateTime(){ this.clock = new Data().toLocaleString(); } }, created(){ this._timer = setInterval(this.update,1000); }, beforeDestroy(){ this._timer.cancel(); }, template:`<div>{{clock}}</div>` }; //注册组件,名为myclock Vue.component("myclock",myclock); //注册组件,名为myclick Vue.component("myclick", mytemplate1) //注册组件,名为incbutton Vue.component("incbutton", myTemplate); var vm = new Vue({ el: "#app" }); </script> </body> </html>
将组件封装成js文件 然后调用。incbutton.js
//定义组件 var myTemplate = { // ` 模板字符串 ` es6,随便换行,缺点 --> 兼容性不太行 只能在es6环境中运行 // '' // "" template:` <div>使用说明 <ul> <li>点击一下,数字增加</li> <li>如果大于0,鼠标移到按钮上去减1啦</li> </ul> <button @click='incr' @mouseover='decr' >你已经点击了{{count}}</button> </div>`, data() { return { count:0 } }, methods:{ incr(){ this.count = this.count +1 ; }, decr(){ this.count = this.count >0 ? this.count -1:0; } } };