1. 生命周期主要阶段
1.1. 挂载(初始化相关属性)
- beforeCreate
- created
- beforeMount
- mounted
1.2. 更新(元素或组件的变更操作)
- beforeUpdate
- updated
1.3. 销毁(销毁相关属性)
- beforeDestroy
- destroyed
1.4. 生命周期图示
2. 生命周期例子
2.1. 代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>生命周期</title>
</head>
<body>
<div id="app">
<div>{{msg}}</div>
<button @click='update'>更新</button>
<button @click='destroy'>销毁</button>
</div>
<script type="text/javascript" src="vue.min.js"></script>
<script type="text/javascript">
var vm = new Vue({
el: "#app",
data: {
msg: '生命周期'
},
methods: {
update: function(){
this.msg = 'hello';
},
destroy: function(){
this.$destroy();
}
},
// 挂载
beforeCreate: function(){
console.log('beforeCreate');
},
created: function(){
console.log('created');
},
beforeMount: function(){
console.log('beforeMount');
},
mounted: function(){
console.log('mounted');
},
// 更新
beforeUpdate: function(){
console.log('beforeUpdate');
},
updated: function(){
console.log('updated');
},
// 销毁
beforeDestroy: function(){
console.log('beforeDestroy');
},
destroyed: function(){
console.log('destroyed');
}
});
</script>
</body>
</html>
2.2. 效果图
2.3. 点击更新按钮
2.4. 点击销毁按钮