目录
vue生命周期
每个vue实例在被创建时都要经过一些列的初始化过程----需要设置数据监听,编译模式,将实例挂载到DOM并在数据变化时更新DOM等情况下需要使用。 同时在这个过程中也会运行一些叫做生命周期狗仔的函数, 这给用户在不同阶段添加自己的代码的机会。
官网生命周期示例图
vue生命周期钩子函数
示范
组件创建,开启定时任务,定时打印hello,在destoryed中对定时器进行销毁。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="./vue/vue.js"></script>
</head>
<body>
<h1>vue生命周期示范</h1>
<div id="app">
<button @click="handleShow">点我组件消失</button>
<hr>
<child v-if="show"></child>
<hr>
</div>
</body>
<script>
//定义一个全局组件
Vue.component('child',{
template:`
<div>
<button>后退</button>
{{title}}
<button @click="handleClick">前进</button>
</div>`,
data(){
return {
title:'好看的首页',
t:''
}
},
methods:{
handleClick(){
alert('前进')
this.title = 'yietong'
}
},
beforeCreate() {
console.log('beforeCreate')
console.log(this.$data)
console.log(this.$el)
},
created() {
console.log('created')
console.log(this.$data)
console.log(this.$el)
// 开启定时器,每隔3s,打印hello
this.t=setInterval(()=>{
console.log('hello')
},3000)
},
beforeMount() {
console.log('beforeMount')
console.log(this.$data)
console.log(this.$el)
},
mounted() {
console.log('mounted')
console.log(this.$data)
console.log(this.$el)
},
beforeUpdate() {
console.log('beforeUpdate')
},
updated() {
console.log('updated')
},
beforeDestroy() {
console.log('当前状态:beforeDestroy')
},
destroyed() {
console.log('当前状态:destroyed')
// 销毁定时器
clearInterval(this.t)
this.t=null
},
})
var vm = new Vue({
el:'#app',
data:{
show:true
},
methods:{
handleShow(){
this.show = !this.show
}
}
})
</script>
</html>