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.

Data<br />

In addition to reusable markup, components allow us to reuse JavaScript<br />

functionality. The configuration object can not only include a template but can<br />

also include its own state, just like the <strong>Vue</strong> instance. In fact, each component can<br />

be thought of as a mini-instance of <strong>Vue</strong> with its own data, methods, lifecycle<br />

hooks, <strong>and</strong> so on.<br />

We treat component data slightly differently to the <strong>Vue</strong> instance though, as<br />

components are meant to be reusable. For example, we might create a bank of<br />

check-box components like this: <br />

<br />

<strong>Vue</strong>.component('check-box', { template: '' data: { checked: false } }); <br />

As it is, if a user clicks a checkbox div, the checked state toggles from true to false<br />

for every checkbox simultaneously! This is not what we want, but it is what will<br />

happen, as all instances of the component refer to the same data object <strong>and</strong><br />

therefore have the same state.<br />

To give each instance its own unique state, the data property shouldn't be an<br />

object, but a factory function that returns an object. That way, every time the<br />

component is instantiated, it links to a fresh data object. Implementing this is as<br />

simple as: data() { return {<br />

checked: false<br />

} }

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

Saved successfully!

Ooh no, something went wrong!