1、代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>生命周期</title>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script type="text/javascript" src="./js/dayjs.min.js"></script>
<style>
</style>
</head>
<body>
<div id="root">
<h2 :style="{opacity}">欢迎学习vue</span></h2>
</div>
<script type="text/javascript">
Vue.config.productionTip=false;
new Vue({
el:"#root",
data:{
opacity:1,
},
//vue完成模板解析并把真实的Dom元素放入页面后(挂载完毕)调用mounted
mounted(){
console.log('mounted');
setInterval(()=>{
this.opacity -=0.01;
if (this.opacity<=0){
this.opacity=1
}
},16)
}
})
</script>
</body>
</html>
效果
引出生命周期
2、挂载流程
验证 beforeCreate
beforeCreate(){
console.log('beforecreate');
console.log(this);
debugger;
}
验证created
created(){
console.log('created');
console.log(this);
debugger;
}
可以通过vm访问到data中的数据、methods中配置方法。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>生命周期总结</title>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script type="text/javascript" src="./js/dayjs.min.js"></script>
<style>
</style>
</head>
<body>
<div id="root">
<h2 v-text="n"></h2>
<h2 >当前的n值是{{n}}</span></h2>
<button @click="addn"> 点击n++</button>
<button @click="bye"> 点我销毁vm</button>
</div>
<script type="text/javascript">
Vue.config.productionTip=false;
new Vue({
el:"#root",
data:{
n:1,
},
methods:{
addn(){
this.n++;
},
bye(){
console.log('bye');
this.$destroy();
}
},
beforeCreate(){
console.log('beforecreate');
//console.log(this);
//debugger;
},
created(){
console.log('created');
//console.log(this);
//debugger;
},
beforeMounted(){
console.log('beforeMounted');
},
mounted() {
console.log('mounted');
},
beforeUpdate(){
console.log('beforeUpdate');
},
updated(){
console.log('updated');
},
beforeDestroy(){
console.log('beforetroy');
},
detroyed(){
console.log('detroyed');
}
})
</script>
</body>
</html>
清除定时器
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>生命周期</title>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script type="text/javascript" src="./js/dayjs.min.js"></script>
<style>
</style>
</head>
<body>
<div id="root">
<h2 :style="{opacity}">欢迎学习vue</span></h2>
<button @click="opacity=1">透明度设置为1</button>
<button @click="stopChange">点击我停止变换</button>
</div>
<script type="text/javascript">
Vue.config.productionTip=false;
new Vue({
el:"#root",
data:{
opacity:1,
},
methods:{
stopChange(){
//clearInterval(this.timer);
this.$destroy();//强制停止
}
},
//vue完成模板解析并把真实的Dom元素放入页面后(挂载完毕)调用mounted
mounted(){
console.log('mounted');
this.timer= setInterval(()=>{
this.opacity -=0.01;
if (this.opacity<=0){
this.opacity=1
}
},16)
},
beforeDestroy(){
console.log("vm即将驾鹤西游");
clearInterval(this.timer);
}
})
</script>
</body>
</html>
总结: