分為4個階段:
create/mount/update/destroy
每一個階段都對應着有自己的處理函數
create: beforeCreate created
初始化
mount: beforeMount mounted
和掛載相關的處理
update: beforeUpdate updated
根據要更新的數據 做邏輯判斷
destroy:beforeDestroy destroyed
清理工作
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>生命周期</title> <script src="js/vue.js"></script> </head> <body> <div id="container"> <p>{{msg}}</p> <!--點擊的時候isShow進行取反 --> <button @click="isShow = !isShow">切換是否顯示組件</button> <my-component v-if="isShow"></my-component> </div> <script> Vue.component("my-component",{ template:` <div> <button @click="handleClick">Click Me</button> <h1>component:{{count}}</h1> </div> `, data:function(){ return { count:0 } }, methods:{ handleClick:function(){ this.count++; } }, beforeCreate: function () { console.log('准備創建組件'); }, created: function () { console.log('組件創建完畢'); }, beforeMount: function () { console.log('組件的模板准備掛載到DOM'); }, mounted: function () { console.log('掛載完畢'); }, beforeUpdate: function () { console.log('准備更新了'); }, updated:function(){ console.log('更新完成'); }, beforeDestroy: function () { console.log('准備destroy'); }, destroyed: function () { console.log('destroy完成'); } }) new Vue({ el:"#container", data:{ msg:"Hello VueJs", isShow:true } }) </script> </body> </html>
生命周期練習,需要那階段寫那個階段
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>生命周期練習</title> <script src="js/vue.js"></script> </head> <body> <div id="container"> <p>{{msg}}</p> <my-component></my-component> </div> <script> Vue.component("my-component",{ data:function(){ return { myOpacity:0 } }, template:` <h1 v-bind:style="{opacity:myOpacity}">透明度將改變 </h1>`, mounted:function(){ setInterval(function(){ this.myOpacity += 0.1; if(this.myOpacity>1){ this.myOpacity = 0; } }.bind(this),1000) } }) new Vue({ el:"#container", data:{ msg:"Hello VueJs" } }) </script> </body> </html>