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.

Refs<br />

In its initial state, the modal window is hidden with a display: none CSS rule. To<br />

open the modal, the user must click the header image. A click event listener will<br />

then set the root instance data property modelOpen to true, which will, in turn, add a<br />

class to the modal to overwrite the display: none to display: block.<br />

After refactoring, however, modalOpen has been moved into the ModalWindow<br />

component along with the rest of the modal logic, <strong>and</strong> hence the modal opening<br />

functionality is currently broken. One possible way to fix this is to let the root<br />

instance manage the opened/closed state of the modal by moving the logic back<br />

into the root instance. We could then use a prop to inform the modal when it<br />

needs to open. When the modal is closed (this happens in the scope of the modal<br />

component, where the close button is) it would send an event to the root instance<br />

to update the state.<br />

This approach would work, but it's not in the spirit of making our components<br />

decoupled <strong>and</strong> reusable; the modal component should manage its own state.<br />

How, then, can we allow the modal to keep its state, but let the root instance (the<br />

parent) change it? An event won't work, as events can only flow up, not down.<br />

ref is a special property that allows you to directly reference a child component's<br />

data. To use it, declare the ref property <strong>and</strong> assign it a unique value, such as<br />

imagemodal.<br />

resources/views/app.blade.php: ... <br />

Now the root instance has access to this specific ModalWindow component's data via<br />

the $refs object. This means we can change the value of modalOpen inside a root<br />

instance method, just like we could from within ModalWindow.<br />

resources/assets/<strong>js</strong>/app.<strong>js</strong>: var app = new <strong>Vue</strong>({ ... methods: { openModal() {<br />

this.$refs.imagemodal.modalOpen = true; }, } });<br />

Now we can call the openModal method in the header image's click listener, thus

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

Saved successfully!

Ooh no, something went wrong!