vue生命周期
1.实例创建
beforecreate()实例创建之前
created()实例创建后
<template>
<div ref="tdiv">
{{message}}
</div>
</template>
<script>
export default {
data () {
return {
message:'hello world'
}
},
methods: {
changeMsg () {
this.message = 'goodbye world'
}
},
beforeCreate () {
console.log('------初始化前------')
console.log(this.message)
console.log(this.$refs.tdiv)
},
created(){
console.log('------初始化完成------')
console.log(this.message)
console.log(this.$refs.tdiv)
}
</script>
运行上面的代码我们获取的是
------初始化前------
undefined
undefined
------初始化完成------
hello world
undefined
证明了在beforeCreate()中 vue实例未创建 this不能使用 页面DOM也不能获取
在created()中实例创建完 可以获取data的数据 但是仍然不能获取页面DOM元素
2.数据挂载
beforeMount ()数据挂载之前
mounted() 数据挂载之后
<template>
<div @click="changeMsg" ref="tdiv">
{{message}}
</div>
</template>
<script>
export default {
data () {
return {
message:'hello world'
}
},
methods: {
changeMsg () {
this.message = 'goodbye world'
}
},
beforeMount () {
console.log('------挂载前---------')
console.log(this.message)
console.log(this.$refs.tdiv)
},
mounted () {
console.log('------挂载完成---------')
console.log(this.message)
console.log(this.$refs.tdiv)
},
</script>
运行上面的代码我们获取的是
------挂载前------
hello world
<div @click="changeMsg" ref="tdiv">
{{message}}
</div>
------挂载完成------
hello world
<div>
hello world
</div>
在挂载前和挂载后的打印中 我们能明显发现 他们的主要区别在于页面元素是否渲染
3.数据更新
beforeUpdate(更新前)
updated(更新后)
当 data 变化时,会触发beforeUpdate方法 。data 数据尚未和最新的数据保持同步。
当数据页面和 data 数据已经保持同步了 ,会触发 updated 方法。
两个钩子函数最明显的变化是在视图更新上
4.实例销毁
beforeDestory(销毁前)
destoryed(销毁后)
组件销毁之前调用 ,在这一步,实例仍然完全可用。
组件销毁之后调用,对 data 的改变不会再触发周期函数,vue 实例已解除事件监听和 dom绑定,但 dom 结构依然存在。