Premium Economy Software


Singapore
Perth W Australia

How a child’s $emit to the parent with Vue.js Works

May 13, 2017 Uncategorized 0 comments

Vue.js is pretty cool and has some cool features. But one confusing feature is called components. Now I hate this technical jargon and it took me 2 hours to figure this out, mainly because of all the confusing Jargon. Why don’t coders speak like real people?

 

Component

I assume you know what a Vue.js component is. So image you have

A Parent  —- >   A Child

 

Now let’s image a real world scenario. A parent has thrown a ball to the child. The parent wants to know if the child has caught the ball.

 

Child   –  Catches Ball              >>>  Parent  – On Hearing (got it!)
– Shouts (emits) Got it                       – Says “He’s got it”

So all $emit does is ‘shouts’ a key word (event) and all the parent has to do is listen for that Shout. It’s that simple.

 

Let’s see how it looks in a code.

 

<h2> My Vue Tutorial </h2>
<div id='app' class='display'>

<ol>
<todo-item @i-got-it="parentClick"></todo-item>
</ol>
END
</div>

<template id='t1'>
<div>
<li>This is a todo {{name}} </li>
<a  v-on:click='childGotBall'> click me 2 </a>
</div>
</template>

 

<script>
Vue.component('child', {
template: '#t1',

methods: {
childGotBall() {
alert('Child got ball')
this.$emit('i-got-it',1)
}
}
})

var app = new Vue({
el: '#app',

methods: {
parentSays() {
alert('My Child Has It')
}

}
//---

})