Vue实例有一个完整的生命周期,也就是从开始创建、初始化数据、编译模板、挂载Dom、渲染→更新→渲染、卸载等一系列过程,我们称这是Vue的生命周期。通俗说就是Vue实例从创建到销毁的过程,就是生命周期。
在组件中具体的方法有:
beforeCreate、created(此时需说明可以在created中首次拿到data中定义的数据)、beforeMount、mounted(此时需说明dom树渲染结束,可访问dom结构)、beforeUpdate、updated、beforeDestroy、destroyed
下面是Vue生命周期的流程图:
下面是一个检验lifeCycle的小程序:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="../vue.js"></script>
<title>lifeCycle</title>
</head>
<body>
<div id="app">
<h1 :style="{opacity}">你好世界</h1>
<button @click="onclick()">点我透明度变高</button>
</div>
<script>
let vm=new Vue({
el:'#app',
data:{
opacity: 1
},
methods:{
onclick(){
this.opacity-=0.2;
}
},
computed:{
},
beforeCreate() {
console.log("beforeCreate,啥都没做")
},
created() {
console.log("created,配置了代理对象vm")
},
beforeMount() {
console.log("beforeMount,有虚拟dom但还没有挂载到真实dom")
},
mounted() {
console.log("mounted,挂载虚拟dom")
},
beforeUpdate() {
console.log("beforeUpdate,更新了数据但还没改变到页面上")
},
updated() {
console.log("updated,数据和页面展示均已更新")
},
beforeDestroy() {
console.log("beforeDestroy,收尾工作,关闭定时器,解绑自定义事件,取消订阅消息等")
},
destroyed() {
console.log("destroyed,销毁data,methods,指令等...")
},
})
</script>
</body>
</html>