Events

Events are used in two ways — the recipient that subscribes to an event and the emitter that fires it, very much like Angular's concept of output and EventEmitter.

To subscribe to an event, you use the at sign (@) — @event="expr". On the left side of the equation, the event corresponds to the event name, while the expression on the right specifies what to execute, usually a certain method.

On the other end, when a child component needs to trigger an event, you use a function provided to you by Vue called $emit, passing it the event name and relevant payload if needed, as shown in the following example:

this.$emit('click', 'some payload');

To demonstrate events, let's change the Parent component to subscribe to an update event fired by the child component, as shown in the following example:

<template>
<div>
<Child @update="changeName" :greet="name" />
</div>
</template>

<script>
import Child from './Child.vue';

export default {
name: 'Parent',
components: {
Child,
},
data: () => ({
name: 'John Doe',
}),
methods: {
changeName: function(newName) {
this.name = newName;
}
},
}
</script>

Then, let's change the Child component to fire an update event when a button is pressed, as shown in the following example:

<template>
<div>
<span>Hello {{ greet }}</span>
<button @click="changeNameClicked">Change Name</button>
</div>
</template>

<script>
export default {
name: 'Child',
props: {
greet: String,
},
methods: {
changeNameClicked: function() {
this.$emit('update', 'Jane');
}

},
}
</script>

What happens here?
When the button is clicked, the child component fires an event named update with a string payload of Jane. Having the parent subscribed to this event triggers the parent component's changeName method.
Then the method changes the data called name, which eventually triggers the Vue rendering process, resulting in passing down the new value to the child component and, finally, in the rendering of Hello Jane.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.158.36