25.06.2018 Views

Full-Stack Vue.js 2 and Laravel 5

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Figure 2.11. <strong>Vue</strong>.<strong>js</strong> lifecycle diagram <strong>Vue</strong> allows you to execute custom logic at these different steps via<br />

lifecycle hooks, which are callbacks defined in the configuration object.<br />

For example, here we utilize the beforeCreate <strong>and</strong> created hooks: new <strong>Vue</strong>({ data: {<br />

message: 'Hello' }, beforeCreate: function() { console.log('beforeCreate<br />

message: ' + this.message); // "beforeCreate message: undefined" }, created:<br />

function() { console.log('created: '+ this.message); // "created message: Hello" },<br />

});<br />

<strong>Vue</strong> will alias data properties to the context object after the beforeCreate hook is<br />

called but before the created hook is called, hence why this.message is undefined in<br />

the former.<br />

The caveat I mentioned earlier about the Escape key listener is this: although<br />

unlikely, if the Escape key was pressed <strong>and</strong> our callback was called before <strong>Vue</strong><br />

has proxied the data properties, app.modalOpen would be undefined rather than true<br />

<strong>and</strong> so our if statement would not control flow like we expect.<br />

To overcome this we can set up the listener in the created lifecycle hook that will<br />

be called after <strong>Vue</strong> has proxied the data properties. This gives us a guarantee that<br />

modalOpen will be defined when the callback is run.<br />

app.<strong>js</strong>: function escapeKeyListener(evt) { if (evt.keyCode === 27 &&<br />

app.modalOpen) { app.modalOpen = false; } } var app = new <strong>Vue</strong>({ data: { ... },<br />

watch: { ... }, created: function() { document.addEventListener('keyup',<br />

escapeKeyListener); } });

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!