vue2
测试用
beforeCreate() {
console.log("beforeCreate");
}, //数据监测及数据代理实现之前
created() {
console.log("created");
}, //数据监测及数据代理实现之后
beforeMount() {
console.log("beforeMount");
}, //虚拟DOM转为真实DOM之前
mounted() {
console.log("mounted");
}, //虚拟DOM转为真实DOM之后
beforeUpdate() {
console.log("beforeUpdate");
}, //数据更新引发的页面更新之前(数据与页面不一致)
updated() {
console.log("updated");
}, //数据更新引发的页面更新之后
beforeDestroy() {
console.log("beforeDestroy");
}, //vue实例卸载(崩溃)前(数据依然可用,但是更改数据,无法引发页面更新)
destroyed() {
console.log("destroyed");
}, //vue实例卸载(崩溃)后
activated() {//进入路由页面会打印,登录进来好像没有打印
//路由激活
console.log("activated");
},
deactivated() {
//路由失活
console.log("deactivated");
},
生命周期之八守卫
//vue初始化,但数据代理还未开始
beforeCreate() {},//数据监测及数据代理实现之前
created() {},//数据监测及数据代理实现之后
//---解析模板,生成虚拟DOM---
beforeMount() {},//虚拟DOM转为真实DOM之前
mounted() {},//虚拟DOM转为真实DOM之后
//---数据改变,数据更新---
beforeUpdate() {},//数据更新引发的页面更新之前(数据与页面不一致)
updated() {},//数据更新引发的页面更新之后
beforeDestroy() {},//vue实例卸载(崩溃)前(数据依然可用,但是更改数据,无法引发页面更新)
destroyed() {},//vue实例卸载(崩溃)后
图示
常用的生命周期钩子
-
mounted: 发送ajax请求、启动定时器、绑定自定义事件、订阅消息等初始化操作。
-
beforeDestroy: 清除定时器、解绑自定义事件、取消订阅消息等收尾工作。
关于销毁Vue实例
-
销毁后借助Vue开发者工具看不到任何信息。
-
销毁后自定义事件会失效,但原生DOM事件依然有效。
-
一般不会在beforeDestroy操作数据,因为即便操作数据,也不会再触发更新流程了。
路由中的生命周期钩子
作用
路由组件所独有的两个钩子,用于捕获路由组件的激活状态。
具体使用:
`activated`路由组件被激活时触发。
`deactivated`路由组件失活时触发。
vue3
vue2生命周期与vue3生命周期对比
-
Vue3.0中可以继续使用Vue2.x中的生命周期钩子,但有有两个被更名:
beforeDestroy改名为beforeUnmountdestroyed改名为unmounted
-
Vue3.0也提供了 Composition API 形式的生命周期钩子,与Vue2.x中钩子对应关系如下:
beforeCreate===>setup()created=======>setup()beforeMount===>onBeforeMountmounted=======>onMountedbeforeUpdate===>onBeforeUpdateupdated=======>onUpdatedbeforeUnmount==>onBeforeUnmountunmounted=====>onUnmounted