Vue的生命周期
- beforeCreated
beforeCreate:function(){
//组件创建之前
console.log(this) //对象已经创建了,但是还没有开始加载数据
console.log(this.msg) //undefined
},
- created
created:function () {
//组件创建之后
console.log(this.msg)
//使用该组件就会调用created方法
// 一般用来发送ajax请求,操作后端数据
},
- beforeMount
beforeMount:function () {
// 取不到,vue还没有开始渲染
console.log(document.getElementById("child"))
},
- mounted
mounted:function () {
// 取到了,vue已经渲染过了
// 应用,操作DOM
console.log(document.getElementById("child"))
},
- beforeUpdate
beforeUpdate:function () {
// 在更新DOM前调用
// 获取原始的DOM
console.log('before update......')
console.log(document.getElementById('app').innerHTML)
},
- updated
updated:function () {
// 更新DOM之后调用 获取更新之后的DOM
// (必须是写在body中的标签,单纯的改变msg数据并不会触发)
console.log('updated......')
console.log(document.getElementById('app').innerHTML)
}
- beforeDestroy
beforeDestroy:function () {
// 销毁之前
console.log('before Destroy......')
console.log(this)
},
- destroyed
destroyed:function () {
// 销毁之后
console.log('Destroyed......')
console.log(this)
}
因为频繁的创建和销毁组件太过占用内存,所有vue提供的特殊的模板可以将组件缓存起来,这样就可以保存组件停用前的状态,以便在下次激活时直接使用,并且提供了activated和deactivated方法作为激活和停用的钩子。
设置缓存
<keep-alive>
<App v-if="isShow"></App>
</keep-alive>
- activated
activated:function () {
console.log("组件被激活了...")
},
- deactivated
deactivated:function () {
console.log("组件被停用了...")
}