官术网_书友最值得收藏!

Lifecycle hooks

When your main script is run and your instance of Vue is set up, it goes through a series of initialization steps. As we said earlier, Vue will walk through your data objects and make them reactive, as well as compile the template and mount to the DOM. Later in the lifecycle, Vue will also go through updating steps, and later still, tear-down steps.

Here is a diagram of the lifecycle instance taken fromhttp://vuejs.org. Many of these steps concern concepts that we haven't yet covered, but you should get the gist:

Figure 2.11. Vue.js lifecycle diagram

Vue allows you to execute custom logic at these different steps vialifecycle hooks,which are callbacks defined in the configuration object.

For example, here we utilize thebeforeCreateandcreatedhooks:

new Vue({
  data: {
    message: 'Hello'
  },
  beforeCreate: function() {
    console.log('beforeCreate message: ' + this.message);
    // "beforeCreate message: undefined"
  },
  created: function() {
    console.log('created: '+ this.message);
    // "created message: Hello"
  },
});

Vue will alias data properties to the context objectafterthebeforeCreatehook is called butbeforethecreatedhook is called, hence whythis.messageisundefinedin the former.

The caveat I mentioned earlier about theEscapekey listener is this: although unlikely, if theEscapekey was pressed and our callback was calledbeforeVue has proxied the data properties,app.modalOpenwould beundefinedrather thantrueand so ourifstatement would not control flow like we expect.

To overcome this we can set up the listener in thecreatedlifecycle hook that will be calledafterVue has proxied the data properties. This gives us a guarantee thatmodalOpenwill be defined when the callback is run.

app.js:

function escapeKeyListener(evt) {
  if (evt.keyCode === 27 && app.modalOpen) {
    app.modalOpen = false;
  }
}

var app = new Vue({
  data: { ... },
  watch: { ... },
  created: function() {
    document.addEventListener('keyup', escapeKeyListener);
  }
});
主站蜘蛛池模板: 河南省| 泰兴市| 上杭县| 赤壁市| 樟树市| 恭城| 彭泽县| 渝北区| 永和县| 抚州市| 泰安市| 桐梓县| 九寨沟县| 湖南省| 利川市| 高邮市| 甘德县| 焦作市| 汝州市| 房山区| 德庆县| 交城县| 若尔盖县| 镶黄旗| 屏山县| 托里县| 宿松县| 洛川县| 延庆县| 平乡县| 西昌市| 丰顺县| 兰西县| 黑河市| 太和县| 灌云县| 四会市| 郯城县| 东港市| 射洪县| 中江县|