内容简介:图中红色标红的函数生命周期函数中的this默认绑定到该vue实例,所以不要使用箭头函数,会出现this绑定错误。: 可获取vue实例,data数据未绑定,el未挂载。所以不要在此函数内对数据做任何修改,因为数据undefined。
生命钩子函数/周期函数
图中红色标红的函数
created() {
}
mounted() {
}
复制代码
生命周期函数中的this默认绑定到该vue实例,所以不要使用箭头函数,会出现this绑定错误。
生命周期各个阶段
beforeCreate
<div id="app">hello world</div>
var vm=new Vue({
el:'#app',
template:'<div>hello vue</div>'
data:{
a:1
},
beforeCreate() {
console.log('beforeCreate') // beforeCreate
console.log(this) // Vue$3
console.log(this.$el) // undefined
console.log(this.a) // undefined
}
})
复制代码
: 可获取vue实例,data数据未绑定,el未挂载。所以不要在此函数内对数据做任何修改,因为数据undefined。
created
<div id="app">hello world</div>
var vm=new Vue({
el:'#app',
template:'<div>hello vue</div>'
data:{
a:1
},
created() {
console.log('created') // created
console.log(this) //Vue$3
console.log(this.$el) // undefined
console.log(this.a) // 1
}
})
复制代码
: 数据已挂载,el未挂载,适合初始化数据。
beforeMount
-
没有
el属性当没有el属性时,该函数不会被调用,只有当调用$mount函数时才会被调用。
var vm=new Vue({
data:{
a:1
},
beforeMount() {
console.log('beforeMount') // 没有任何输出
}
})
vm.$mount('#app')
// beforeMount
复制代码
-
没有
template属性没有template属性时,el外部的html被当成template进行渲染
var vm=new Vue({
el:'#app',
data:{
a:1
},
beforeMount() {
console.log('beforeMount') // beforeMount
console.log(this) // Vue$3
console.log(this.$el) // <div id="app">hello world</div>
console.log(this.a) // 1
}
})
复制代码
template
属性
var vm=new Vue({
el:'#app',
template:'<div>hello vue</div>'
data:{
a:1
},
beforeMount() {
console.log('beforeMount') // beforeMount
console.log(this.$el) // 注意!! <div id="app">hello world</div>
}
})
复制代码
: 渲染template,但el仍未挂载
mounted
var vm=new Vue({
el:'#app',
template:'<div>hello vue</div>'
data:{
a:1
},
mounted() {
console.log('mounted') // mounted
console.log(this.$el) // 注意!! <div>hello vue</div>
}
})
复制代码
: 挂载el,将el标识的dom元素整个替换成template渲染成的dom元素。
beforeUpdate/updated
当绑定的数据变化时,先调用beforeUpdate函数,任何更新虚拟dom,重新渲染,然后调用updated。
注意:只有绑定在模板里渲染的数据变动才会调用这两个函数。
var vm=new Vue({
el:'#app',
template:'<div>hello vue</div>',
data:{
a:1
},
beforeUpdate() {
console.log('beforeUpdate')
},
updated() {
console.log('updated')
}
})
vm.a=2 // 没有任何输出
var vm=new Vue({
el:'#app',
template:'<div>hello vue!!!{{a}}</div>',
data:{
a:1
},
beforeUpdate() {
console.log('beforeUpdate')
},
updated() {
console.log('updated')
}
})
vm.a=2 // beforeUpdate updated
复制代码
调用vm.$destory()后调用beforeDestroy(),移除监听器、数据解绑、销毁子实例后调用destroyed()
以上所述就是小编给大家介绍的《vue-生命周期》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
About Face 3 交互设计精髓
Alan Cooper、Robert Reimann、David Cronin / 刘松涛 / 电子工业出版社 / 2008-11 / 72.00元
本书是一本数字产品和系统的交互设计指南,全面系统地讲述了交互设计过程、原理和方法,涉及的产品和系统有个人电脑上的个人和商务软件、Web应用、手持设备、信息亭、数字医疗系统、数字工业系统等。运用本书的交互设计过程和方法,有助于了解使用者和产品之间的交互行为,进而更好地设计出更具吸引力和更具市场竞争力的产品。 全书分成3篇:第1篇描述了“目标导向设计”,详细讨论了用户和设计的过程及思想;第2篇讲......一起来看看 《About Face 3 交互设计精髓》 这本书的介绍吧!