1. 生命周期图
2.生命周期运行过程代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue实例的生命周期</title>
</head>
<body>
<div id="app">
<h1>测试生命周期</h1>
<div>{{msg}}</div>
<hr>
<h3>测试beforeUpdate和update两个钩子函数</h3>
<button @click="handlerUpdate">更新数据</button>
</div>
<script src="vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
msg: "12345"
},
methods: {
handlerUpdate() {
this.msg=this.msg.split("").reverse().join("")
}
},
//按照示意图依次调用
beforeCreate(){
console.log("调用了beforeCreate钩子函数");
},
created(){
console.log("调用了created钩子函数");
},
beforeMount(){
console.log('调用了beforeMount钩子函数');
},
mounted(){
console.log('调用了mounted钩子函数');
},
beforeUpdate(){
console.log("调用了beforeUpdate钩子函数")
},
updated(){
console.log("调用了updated钩子函数");
},
beforeDestroy(){
console.log("调用了beforeDestroy钩子函数");
},
destroyed(){
console.log("调用了destroyed钩子函数");
}
})
</script>
</body>
</html>
初始化页面依次调用了:
调用了beforeCreate钩子函数
调用了created钩子函数
调用了beforeMount钩子函数
调用了mounted钩子函数
点击更新数据后:
12345变成了,此时调用了:54321
调用了beforeUpdate钩子函数
调用了更新的钩子函数
打开F12控制台 直接输入主动销毁Vue实例调用:app.$destroy()
调用了beforeDestroy钩子函数
调用了destroyed钩子函数