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

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);
  }
});
主站蜘蛛池模板: 遂溪县| 长子县| 托克托县| 永仁县| 南川市| 灌南县| 宁安市| 乌苏市| 长宁县| 青冈县| 华池县| 禹州市| 德阳市| 大石桥市| 康乐县| 赤峰市| 曲阜市| 晋宁县| 高雄市| 张家港市| 波密县| 南投市| 黄陵县| 阿坝| 虹口区| 永城市| 汝南县| 武功县| 贺州市| 黎平县| 德格县| 东阿县| 双流县| 黄冈市| 灯塔市| 吉木萨尔县| 富裕县| 天祝| 营山县| 长兴县| 和顺县|