25.06.2018 Views

Full-Stack Vue.js 2 and Laravel 5

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Custom events<br />

Our carousel controls are displaying nicely, but they still don't do anything!<br />

When they're clicked, we need them to tell ImageCarousel to either increment or<br />

decrement its index value, which will result in the image being changed.<br />

Dynamic props won't work for this task, as props can only send data down from<br />

a parent to a child. What do we do when the child needs to send data up to the<br />

parent?<br />

Custom events can be emitted from a child component <strong>and</strong> listened to by its<br />

parent. To implement this, we use the $emit instance method in the child, which<br />

takes the event name as the first argument <strong>and</strong> an arbitrary number of additional<br />

arguments for any data to be sent along with the event, such as this.$emit('myevent',<br />

'My event payload');.<br />

The parent can listen to this event using the v-on directive in the template where<br />

the component is declared. If you h<strong>and</strong>le the event with a method, any arguments<br />

sent with the event will be passed to this method as parameters.<br />

Consider this example, where a child component, MyComponent, emits an event<br />

called toggle to tell the parent, the root instance, to change the value of a data<br />

property, toggle: <br />

{{ message }}<br />

<strong>Vue</strong>.component('my-component', { template: 'Click me', methods: { clicked: function() {<br />

this.$emit('toggle'); } } });<br />

new <strong>Vue</strong>({ el: '#app', data: { toggle: false }, computed: { message: function() {<br />

return this.toggle ? 'On' : 'Off'; } } });

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

Saved successfully!

Ooh no, something went wrong!