vue生命周期钩子函数
1 <template> 2 <div> 3 <h2>this is from C.vue</h2> 4 </div> 5 </template> 6 7 <script> 8 export default { 9 name: 'C', 10 data () { 11 return { 12 msg: 'hello C.cue', 13 moneyInit: 100 14 } 15 }, 16 computed: { 17 money () { 18 return this.moneyInit * 100 19 } 20 }, 21 methods: { 22 test () { 23 console.log('this is a test') 24 } 25 }, 26 beforeCreate () { 27 console.log('beforeCreate') 28 29 // this的结果是VueComponent 30 console.log('this:', this) 31 // beforeCreate时 data,computed都不能访问,为undefined 32 console.log('this.msg:', this.msg, 'this.money:', this.money) 33 }, 34 created () { 35 console.log('created') 36 // created时,data,computed,methods均能访问 37 console.log('this.msg:', this.msg, 'this.money:', this.money) 38 this.test() 39 } 40 } 41 </script> 42 43 <style lang="scss" scoped> 44 45 </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唯一不同的地方。
1 <template> 2 <div> 3 <div ref="tag">{{msg}}</div> 4 <div>msg1:{{msg1}}</div> 5 <div>msg2:{{msg2}}</div> 6 <button @click="changeMsg">click it</button> 7 </div> 8 </template> 9 10 <script> 11 export default { 12 name: 'C', 13 data () { 14 return { 15 msg: '', 16 msg1: '', 17 msg2: '' 18 } 19 }, 20 methods: { 21 changeMsg () { 22 this.msg = 'hello' 23 // this.msg1没有立即更新,没能获取到更新后的DOM 24 this.msg1 = this.$refs.tag.innerHTML 25 // this.msg2成功渲染,成功获取到了更新后的DOM 26 this.$nextTick(() => { 27 this.msg2 = this.$refs.tag.innerHTML 28 }) 29 } 30 } 31 } 32 </script> 33 34 <style lang="scss" scoped> 35 36 </style>
当时光不再,莫空留遗恨!