vue聲明周期,在每個(gè)聲明周期中都干了些什么?
1, vue的生命周期
- beforeCreate: 組件實(shí)例剛剛被創(chuàng)建,組件屬性計(jì)算之前,如data屬性
- created: 組件實(shí)例創(chuàng)建完成,屬性已綁定,但是DOM還未完成,$el屬性還不存在
- beforeMount:模板編譯/掛載之前
- mounted: 模板編譯/掛載之后
- beforeUpdate: 組件更新之前
- updated: 組件更新之后
- activated: for
keep-alive
,組件被激活時(shí)調(diào)用 - deactivated: for
keep-alive
,組件被移除時(shí)調(diào)用 - beforeDestroy: 組件銷毀前被調(diào)用
- destoryed: 組件銷毀后調(diào)用
ps:下面代碼可以直接復(fù)制出去執(zhí)行
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<script type="text/javascript" src="https://cdn.jsdelivr.net/vue/2.1.3/vue.js"></script>
<body>
<div id="app">{{a}}</div>
<script>
var vm = new Vue({
el: '#app',
data: {
a: 'vuejs',
},
beforeCreate: function() {
console.log('創(chuàng)建前');
console.log(this.a);
console.log(this.$el);
},
created: function() {
console.log('創(chuàng)建之后');
console.log(this.a);
console.log(this.$el);
},
beforeMount: function() {
console.log('mount之前');
console.log(this.a);
console.log(this.$el);
},
mounted: function() {
console.log('mount之后');
console.log(this.a);
console.log(this.$el);
},
beforeUpdate: function() {
console.log('更新之前');
console.log(this.a);
console.log(this.$el);
},
updated: function() {
console.log('更新完成');
console.log(this.a);
console.log(this.$el);
},
beforeDestroy: function() {
console.log('組件銷毀之前');
console.log(this.a);
console.log(this.$el);
},
destroyed: function() {
console.log('組件銷毀之后');
console.log(this.a);
console.log(this.$el);
},
})
</script>
</body>
</html>
beforeCreated: el和data并未初始化
created: 完成data數(shù)據(jù)的初始化,el沒有
beforeMount: 完成了el和data初始化
mounted: 完成掛載
打開命令行在命令行中輸入vm.a = 'change';查看效果
activated
和deactivated
這兩個(gè)生命周期函數(shù)涉及到<keep-alive>
這個(gè)組件,所以想了解這個(gè)生命周期函數(shù)的可以看一下我的另一篇文章
aboutme
github
blog