Each Vue instance goes through a series of initialization processes when it is created - for example, it needs to set up data listeners, compile templates, mount the instance to the DOM and update the DOM when the data changes, etc. At the same time, some functions called lifecycle hooks are also run during this process , which gives users the opportunity to add their own code at different stages.
For example created
hooks can be used to execute code after an instance is created:
new Vue({ data: { a: 1 }, created: function () { // `this` 指向 vm 实例console.log('a is: ' + this.a) }})// => "a is: 1" |
There are also some other hooks that are called at different stages of the instance's life cycle, such as mounted
, updated
and destroyed
. The context of the lifecycle hook this
points to the Vue instance that invoked it.
Don't use arrow functions like created: () => console.log(this.a)
or on option properties or callbacks vm.$watch('a', newValue => this.myMethod())
. Because arrow functions are bound to the parent context, this
they won't be the Vue instance as you might expect, often causing Uncaught TypeError: Cannot read property of undefined
errors Uncaught TypeError: this.myMethod is not a function
like that.