vue組件生命周期詳解
更新時間:2017年11月07日 10:02:12 作者:匿名的girl
這篇文章主要為大家詳細介紹了vue組件生命周期,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了vue組件生命周期的具體代碼,供大家參考,具體內容如下
分為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('準備創(chuàng)建組件'); }, created: function () { console.log('組件創(chuàng)建完畢'); }, 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>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
vue3.0 vue-router4.0打包后頁面空白的解決方法
本文主要介紹了vue3.0 vue-router4.0打包后頁面空白的解決方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-02-02