vue組件生命周期詳解
本文實例為大家分享了vue組件生命周期的具體代碼,供大家參考,具體內容如下
分為4個階段:
create/mount/update/destroy
每一個階段都對應著有自己的處理函數(shù)
create: beforeCreate created
初始化
mount: beforeMount mounted
和掛載相關的處理
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>
<!--點擊的時候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>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
vite+vue3中使用mock模擬數(shù)據(jù)問題
這篇文章主要介紹了vite+vue3中使用mock模擬數(shù)據(jù)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03
vue實現(xiàn)虛擬滾動渲染成千上萬條數(shù)據(jù)
本文主要介紹了vue實現(xiàn)虛擬滾動渲染成千上萬條數(shù)據(jù),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-02-02
vue3.0 vue-router4.0打包后頁面空白的解決方法
本文主要介紹了vue3.0 vue-router4.0打包后頁面空白的解決方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-02-02

