vue組件生命周期詳解
本文實(shí)例為大家分享了vue組件生命周期的具體代碼,供大家參考,具體內(nèi)容如下
分為4個階段:
create/mount/update/destroy
每一個階段都對應(yīng)著有自己的處理函數(shù)
create: beforeCreate created
初始化
mount: beforeMount mounted
和掛載相關(guān)的處理
update: beforeUpdate updated
根據(jù)要更新的數(shù)據(jù) 做邏輯判斷
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>
<!--點(diǎn)擊的時候isShow進(jìn)行取反 -->
<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('準(zhǔn)備創(chuàng)建組件');
},
created: function () {
console.log('組件創(chuàng)建完畢');
},
beforeMount: function () {
console.log('組件的模板準(zhǔn)備掛載到DOM');
},
mounted: function () {
console.log('掛載完畢');
},
beforeUpdate: function () {
console.log('準(zhǔn)備更新了');
},
updated:function(){
console.log('更新完成');
},
beforeDestroy: function () {
console.log('準(zhǔn)備destroy');
},
destroyed: function () {
console.log('destroy完成');
}
})
new Vue({
el:"#container",
data:{
msg:"Hello VueJs",
isShow:true
}
})
</script>
</body>
</html>
生命周期練習(xí),需要那階段寫那個階段
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>生命周期練習(xí)</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>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Vue實(shí)現(xiàn)雙token無感刷新的示例代碼
這篇文章主要介紹了Vue實(shí)現(xiàn)雙token無感刷新,雙token機(jī)制,尤其是指在OAuth 2.0授權(quán)協(xié)議中廣泛使用的access token(訪問令牌)和refresh token(刷新令牌)組合,文中通過代碼示例講解的非常詳細(xì),需要的朋友可以參考下2024-03-03
vite+vue3中使用mock模擬數(shù)據(jù)問題
這篇文章主要介紹了vite+vue3中使用mock模擬數(shù)據(jù)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03
vue實(shí)現(xiàn)虛擬滾動渲染成千上萬條數(shù)據(jù)
本文主要介紹了vue實(shí)現(xiàn)虛擬滾動渲染成千上萬條數(shù)據(jù),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02
詳解從react轉(zhuǎn)職到vue開發(fā)的項(xiàng)目準(zhǔn)備
這篇文章主要介紹了詳解從react轉(zhuǎn)職到vue開發(fā)的項(xiàng)目準(zhǔn)備,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-01-01
vue3.0 vue-router4.0打包后頁面空白的解決方法
本文主要介紹了vue3.0 vue-router4.0打包后頁面空白的解決方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02

