Explain the life cycle hook in Vue instance in detail

  • 2021-08-05 08:22:26
  • OfStack

The entrance of Vue framework is Vue instance, which is actually view model in the framework. It contains business processing logic and data model in the page, and there are multiple event hooks in its life cycle, which makes it easier for us to form good logic when controlling the whole process of Vue instance.

Vue instance

The variable name vm is often used in documents to represent Vue instances. When instantiating Vue, you need to pass in an option object, which can contain data (data), template (template), mount element (el), method (methods), life cycle hook (lifecyclehook) and other options.

Options for Vue instantiation

It should be noted that most functions with this do not use arrow functions, because we expect this to point to Vue instances.

data

The data of the Vue instance is stored in the data object, and Vue will recursively convert the attributes of data to getter/setter, so that the attributes of data can respond to data changes.


var data = { a: 1 }
//  Create directly 1 Instances 
var vm = new Vue({
 data: data
})
vm.a // -> 1
vm.$data === data // -> true

The data is then bound to the HTML, and the Vue framework monitors changes in the data data and automatically updates the HTML content.

computed

The computed attributes will be mixed into the Vue instance. The this context of all getter and setter is automatically bound to Vue

Instance.


var vm = new Vue({
 data: { a: 1 },
 computed: {
 //  Read only, and the value only needs to be a function 
 aDouble: function () {
  return this.a * 2
 },
 //  Read and set 
 aPlus: {
  get: function () {
  return this.a + 1
  },
  set: function (v) {
  this.a = v - 1
  }
 }
 }
})
vm.aPlus // -> 2
vm.aPlus = 3
vm.a  // -> 2
vm.aDouble // -> 4

setter can be omitted here, and if setter is omitted, the value can be a normal function, but there must be a return value.

methods

The methods will be blended into the Vue instance. These methods can be accessed directly through an VM instance or used in instruction expressions. this in the method is automatically bound to an Vue instance.


var vm = new Vue({
 data: { a: 1 },
 methods: {
 plus: function () {
  this.a++
 }
 }
})
vm.plus()
vm.a // 2

Looking at the following example, methods and computed seem to do the same thing, but simply looking at the results is really the same. However, the difference is that computed attributes are cached based on their dependencies. A computed property is re-evaluated only when its related dependencies change. This means that as long as message has not changed, accessing the reversedMessage evaluation property many times will immediately return the previous evaluation result without having to execute the function again. In contrast, the method call always executes this function whenever re-rendering occurs.


var vm = new Vue({
 el: '#example',
 data: {
 message: 'Hello'
 },
 computed: {
 // a computed getter
 reversedMessage: function () {
  // `this` points to the vm instance
  return this.message.split('').reverse().join('')
 }
 }
})

watch

1 object, the key is the expression to be observed, and the value is the corresponding callback function. The value can also be a method name or an object containing options. The Vue instance will call $watch () at instantiation time, traversing every 1 property of the watch object.


var vm = new Vue({
 data: {
 a: 1,
 b: 2,
 c: 3
 },
 watch: {
 //  Monitoring a Automatically execute this function when the variable changes 
 a: function (val, oldVal) {
  console.log('new: %s, old: %s', val, oldVal)
 },
 //  Depth  watcher
 c: {
  handler: function (val, oldVal) { /* ... */ },
  deep: true
 }
 }
})
vm.a = 2 // -> new: 2, old: 1

Lifecycle of an Vue instance

Vue instance has a complete life cycle, that is, a series of processes from creating, initializing data, compiling templates, mounting Dom → rendering, updating → rendering, unloading, etc. We call this the life cycle of Vue. Generally speaking, it is the process from creation to destruction of Vue instance, which is the life cycle.

Throughout the lifecycle of Vue, it provides a number of lifecycle hooks that give us the opportunity to execute custom logic.

Next, let's use a few examples to see how life cycle hooks are used:

HTML structure:


<div id="app">
 <p>{{ number }}</p>
 <input type="text" name="btnSetNumber" v-model="number">
</div>

We bind the number data of the data object to input and p, and the Vue instance is constructed as follows:


var app = new Vue({   
 el: '#app',    
 data: {     
  number: 1
 }
})

In the example, console. log ('Hook Name', this. number) in each life cycle hook, we found that beforeCreate, created, beforeMount and mounted were triggered when the first page was loaded, and data data could be obtained in created.

Go to console. log ('mounted:', document. getElementsByTagName ('p') [0]), DOM rendering has been in mounted
Done.

We try to change the contents of the input input box again, and we can see that the data above the input box changes synchronously. This is the effect of data binding. When updating data, beforeUpdate and updated hooks are triggered, and when beforeUpdate is triggered, the data has been updated.

destroy is only calling app. $destroy (); To destroy the vue instance. After the destruction is complete, we change the value of number again, and vue no longer responds to this action. However, the original generated dom element still exists, so it can be understood that after destroy operation is performed, it is no longer controlled by vue.

Vue.nextTick

A delayed callback is performed after the end of the next DOM update loop. Use this method immediately after modifying the data to get the updated DOM.


Vue.nextTick(function () {
 // DOM  Updated 
})

The official also provides a writing method, vm. $nextTick, which is automatically bound to the instance that calls it with this


created() {
 setTimeout(() => {
   this.number = 100
   this.$nextTick(() => {
   console.log('nextTick', document.getElementsByTagName('p')[0])
   })
 },100)
}

When do I need Vue. nextTick ()

DOM Operation 1 in the created () hook function of the Vue lifecycle must be placed in the callback function of Vue. nextTick (). What's the reason? The reason is that DOM does not actually render when the created () hook function is executed, and it is futile to do DOM operation at this time, so here 1 must put the js code of DOM operation into the callback function of Vue. nextTick (). This corresponds to the mounted hook function, since all DOM mounts and renderings are complete when the hook function is executed, and any DOM operations in the hook function are no problem at this time.

Any action to be performed after data changes that requires an DOM structure that changes with the data should be placed in the callback function of Vue. nextTick ().

Life cycle summary

Some ways to use lifecycle hooks:

beforecreate: You can add an loading event here that fires when the instance is loaded created: Events when initialization completes are written here. If loading events end here, asynchronous requests are also called here mounted: Mount element to get DOM node updated: If data set 1 is processed, write the corresponding function here beforeDestroy: You can make a confirmation box to confirm the stop event nextTick: Operate dom immediately after updating data

Related articles: