4.Vue钩子函数
Vue对象初始化过程调用的函数称为钩子函数;
不应该使用箭头函数来定义一个生命周期方法;
钩子函数调用的时机:
new Vue()
beforeCreate (数据侦听和事件/侦听器的配置之前)
created (数据侦听和事件/侦听器的配置之后)
beforeMount (数据挂载前)
mounted (数据挂载后, 视图的数据被Vue的替换)
beforeUpdate (数据改变,加载到视图前)
updated (加载到视图后)
beforeDestroy (调用vm.$destroy()后,Vue对象销毁前)
destroy (Vue对象销毁后)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| <body> <div id="app"> {{ message }} </div> </body> <script>
let vm = new Vue({ el: '#app', data: { message: 'a' }, beforeCreate: function(){ console.log('beforeCreate'); }, created: function(){ console.log('created'); },
beforeMount: function(){ console.log('beforeMount'); }, mounted: function(){ console.log('mounted'); },
beforeUpdate: function(){ console.log('beforeUpdate'); }, updated: function(){ console.log('updated'); },
activated: function(){ console.log('activated'); }, deactivated: function(){ console.log('deactivated'); },
beforeDestroy: function(){ console.log('beforeDestroy'); }, destroyed: function(){ console.log('destroyed'); },
errorCaptured: function(){ console.log('errorCaptured'); }
}) vm.message = 'b'; setTimeout('vm.$destroy()', 2000); </script>
|
参考API — Vue.js (vuejs.org)