1.生命周期
流程图
相关问题
1. 生命周期有哪些?发送请求在created还是mounted?
Vue2.x系统自带有8个
beforeCreate
created
beforeMount
mounted
beforeUpdate
updated
beforeDestroy
destroyed
具体放在哪:
这个问题具体要看项目和业务的情况了,因为组件的加载顺序是,父组件引入了子组件,那么先执行父的前3个生命周期,再执行子的前4个生命周期,那么如果我们的业务是父组件引入子组件,并且优先加载子组件的数据,那么在父组件中当前的请求要放mounted中,如果当前组件没有依赖关系那么放在哪个生命周期中请求都是可以的。
2. 为什么发送请求不在beforeCreate里? beforeCreate和created有什么区别?
因为:
如果请求是在钩子里直接发起,而不是调用methods里的方法,由于请求是异步的,beforeCreate、created、beforeMount、mounted生命周期函数是同步依次执行的,所以请求在任意钩子里执行都是一样的。
但是
如果请求是在methods封装好了,在beforeCreate调用的时候,beforeCreate阶段 是拿不到methods里面的方法的(会报错)。
区别:
beforeCreate没有$data,created中有$datacreated是可以拿到methods的方法的,beforeCreate拿不到methods的方法
3. 在created中如何获取dom
- 只要写异步代码,获取dom是在异步中获取的,就可以了。
例如:
setTimeout、 请求、Promise.xxx()等等... - 使用vue系统内置的
this.$nextTick
4. 一旦进入组件会执行哪些生命周期?
beforeCreate
created
beforeMount
mounted
5. 第二次或者第N次进去组件会执行哪些生命周期?
如果当前组件加入了keep-alive,只会执行一个生命周期
activated
如果没有加入keep-alive
beforeCreate
created
beforeMount
mounted
6. 父组件引入子组件,那么生命周期执行的顺序是?
父: beforeCreate、 created、 beforeMount
子: beforeCreate、 created、 beforeMount、 mounted
...
父:mounted
I
7. 加入keep-alive会执行哪些生命周期?
如果使用了keep-alive组件,当前的组件会额外增加2个生命周期(系统8 + 2 )
activated
deactivated
如果当前组件加入了keep-alive第一次进入这 个组件会执行5个生命周期
beforeCreate
created
beforeMount
mounted
activated
8. 在什么情况下用过哪些生命周期? 生命周期使用场景
created ===> 单组件请求
mounted ===> 同步可以获取dom,如果先子组件请求后父组件请求
activated ===> 判断id是否相等,如果不相同发起请求
destroyed ===> 关闭页面记录视频播故的时间,初始化的时候从上一次的历史开始播放