vue生命周期钩子函数

时间:2022-12-03 15:58:34

vue生命周期钩子函数

 <template>
<div>
<h2>this is from C.vue</h2>
</div>
</template> <script>
export default {
name: 'C',
data () {
return {
msg: 'hello C.cue',
moneyInit: 100
}
},
computed: {
money () {
return this.moneyInit * 100
}
},
methods: {
test () {
console.log('this is a test')
}
},
beforeCreate () {
console.log('beforeCreate') // this的结果是VueComponent
console.log('this:', this)
// beforeCreate时 data,computed都不能访问,为undefined
console.log('this.msg:', this.msg, 'this.money:', this.money)
},
created () {
console.log('created')
// created时,data,computed,methods均能访问
console.log('this.msg:', this.msg, 'this.money:', this.money)
this.test()
}
}
</script> <style lang="scss" scoped> </style>
<template>
<div id="app">
<div @click="changeMsg">this is from app.vue {{msg}}</div>
<router-link :to="{name:'A'}">to A Page</router-link>
<router-link :to="{name:'B'}" tag="div">to B Page</router-link>
<router-link :to="{name:'C'}">to C Page</router-link>
<router-view/>
</div>
</template> <script>
export default {
name: 'App',
data () {
return {
msg: 'hello'
}
},
methods: {
changeMsg () {
if (this.msg === 'hello') {
this.msg = 'today'
} else {
this.msg = 'hello'
}
}
},
created () {
// created 时 this.$el还不能访问,DOM还未挂载
console.log('created function from App.vue, this.$el:', this.$el)
},
beforeMount () {
// 注意beforeMount的this.$el也为undefined
console.log('beforeMount function from App.vue, this.$el:', this.$el)
},
mounted () {
// mounted 此时this.$el能访问,vue实例挂载到了DOM上
console.log('mounted function from App.vue, this.$el:', this.$el)
},
// data发生变化,即dom发生变化
beforeUpdate () {
console.log('beforeUpdate function from App.vue')
} }
</script> <style>
#app{
display: flex;
flex-direction: column;
align-items: center;
}
</style>

注意几点:

1. created与mounted都常见于ajax请求,前者如果请求响应时间过长,容易白屏

2. mounted不能保证所有子组件都一起被挂载。如果要等到整个视图更新完毕,使用vm.$nextTick()

nextTick:在vue中,用于处理DOM更新操作。vue里面有个watcher,用于观察数据变化,然后更新DOM,vue并不是每次数据更新都会触发DOM更新,而是将这些操作缓存在一个队列。在一个事件循环结束后,刷新队列,统一执行DOM更新。

vm.$nextTick([callback])将回调延时到下次DOM更新循环结束之后执行。在修改数据后使用这个方法,它会获取更新后的DOM。它的this会绑定到调用的实例上,这是与Vue.nextTick唯一不同的地方。

 <template>
<div>
<div ref="tag">{{msg}}</div>
<div>msg1:{{msg1}}</div>
<div>msg2:{{msg2}}</div>
<button @click="changeMsg">click it</button>
</div>
</template> <script>
export default {
name: 'C',
data () {
return {
msg: '',
msg1: '',
msg2: ''
}
},
methods: {
changeMsg () {
this.msg = 'hello'
// this.msg1没有立即更新,没能获取到更新后的DOM
this.msg1 = this.$refs.tag.innerHTML
// this.msg2成功渲染,成功获取到了更新后的DOM
this.$nextTick(() => {
this.msg2 = this.$refs.tag.innerHTML
})
}
}
}
</script> <style lang="scss" scoped> </style>

参考链接:https://juejin.im/entry/5aee8fbb518825671952308c