分為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> <p id="container"> <p>{{msg}}</p> <!--點擊的時候isShow進行取反 --> <button @click="isShow = !isShow">切換是否顯示組件</button> <my-component v-if="isShow"></my-component> </p> <script> Vue.component("my-component",{ template:` <p> <button @click="handleClick">Click Me</button> <h1>component:{{count}}</h1> </p> `, 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> <p id="container"> <p>{{msg}}</p> <my-component></my-component> </p> <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>
相信看了本文案例你已經掌握了方法,更多精彩請關注Gxl網其它相關文章!
推薦閱讀:
vue如何調用mock數據
Vue路由鉤子的實戰使用教程
Vue.js移動端組件庫使用方法
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com