vue2.x生命周期有哪些?
1. 有哪些生命周期?
系统自带8个
1. beforeCreate:在实例初始化之后,数据观测(data observer) 和 event/watcher 事件配置之前被调用。
2. created
3. beforeMount:在挂载开始之前被调用:相关的 render 函数首次被调用。
4. mounted:vm.$el已挂载在文档内,对已有dom节点的操作可以在这期间进行。
5. beforeUpdate
6. updated
7. beforeDestroy:实例销毁之前调用。在这一步,实例仍然完全可用。
8. destroyed:Vue 实例销毁后调用。调用后,Vue 实例指示的所有东西都会解绑定,所有的事件监听器会被移除,所有的子实例也会被销毁。
2. 一旦进入到页面或者组件,会执行哪些生命周期,顺序?
会执行前四个
1. beforeCreate
2. created
3. beforeMount
4. mounted
3. 在哪个阶段有 e l , 在 哪 个 阶 段 有 el,在哪个阶段有 el,在哪个阶段有data?
$el:是组件的根节点
$data:页面的数据
1. beforeCreate:undefined undefined
2. created:undefined data
3. beforeMount:undefined data
4. mounted:el data
以下生命周期$el,$data都有
4. 如果加入了keep-alive会多哪2个生命周期?
(1) activated:keep-alive 组件激活时调用。(进入)
(2) deactivated:keep-alive 组件停用时调用。(离开)
5. 如果加入了缓存组件keep-alive,第一次进入组件会执行哪些生命周期?
1. beforeCreate:undefined undefined
2. created:undefined data
3. beforeMount:undefined data
4. mounted:el data
先执行前面的4个,然后执行activated
6. 如果加入了缓存组件keep-alive,第二次或者第N次进入组件会执行哪些生命周期?
因为页面已经被缓存了,所以只执行activated这一个生命周期
解:生命周期在源码上怎么呈现
//index.html
<div id="app"></div>
<script src="vue.js"></script>
//案例1
new Vue({
beforeCreate(){
console.log('beforeCreate',this.$el,this.$data)//此时的this.$el打
印是有值的,this指向没问题
},
created(){
console.log('created')
},
beforeMount(){
console.log('beforeMount')
},
mounted(){
console.log('mounted')
}
})
//vue.js
class Vue{
constructor(options){
options.beforeCreate()
options.created()
options.beforeMount()
options.mounted()
}
}
//案例2
new Vue({
el:'#app',
data(){
return{
str:'123'
}
},
beforeCreate(){
console.log('beforeCreate',this.$el,this.$data)//此时的this.$el打
印是undefined,this指向是有问题的,需要在类vuede options调用生命周期修改下this的指向
},
created(){
console.log('created')
},
beforeMount(){
console.log('beforeMount')
},
mounted(){
console.log('mounted')
}
})
//vue.js
//当修改了类vue的顺序,那么页面中的生命周期也会改变顺序
class Vue{
constructor(options){
this.$data = options.data
this.$el = document.querySelector(options.el)
console.log(options)//options是对象,打印出来就是上面new Vue对象的生
命周期
此时的this.$el打印是undefined,this指向是有问题的,需要在类vuede
options调用生命周期修改下this的指向
options.beforeCreate()
options.created()
options.beforeMount()
options.mounted()
//修改为
options.beforeCreate.bind(this)()
options.created.bind(this)()
options.beforeMount.bind(this)()
options.mounted.bind(this)()
}
}
//当修改了类vue的顺序,那么页面中的生命周期也会改变顺序
class Vue{
constructor(options){
this.$data = options.data
this.$el = document.querySelector(options.el)
console.log(options)//options是对象,打印出来就是上面new Vue对象的生命周期
//此时的this.$el打印是undefined,this指向是有问题的,需要在类vuedeoptions调用生命周期修改下this的指向
//修改为
options.beforeCreate.bind(this)()
options.created.bind(this)()
options.beforeMount.bind(this)()
options.mounted.bind(this)()
}
}