Saturday 25 June 2022

props vs emit in vue.js

 In my last article here , I tried to explain about data(), props, methods and components. Here I’m gonna explain about emit function of vue.js.

<template>
<div>
<input type="text" v-model="firstName"/>
<input type="text" v-model="lastName"/>
<br/>
<button @click='onButtonClick()'>
Click Me
</button>
</div>
</template>
<script>
export default {

props: ['firstName', 'lastName'],

emits: ['onClick'],

methods :{
onButtonClick($event){
this.$emit("onClick", { fName: this.firstName, lName:this.lastName});
}
},

}
</script>
<script>
import MyComp from './MyComponent.vue' //import the component
export default {

components: {
'my-comp' : MyCompl //define the component
},

data() {
return {
firstName: 'Binod',
lastName: 'Mahto',
fullName:'',
}
},

methods : {
mtdCalculateFullName(payload) {
this.$data.firstName = payload.fName;
this.$data.lastName = payload.lName;
this.$data.fullName = this.$data.firstName + ' ' + this.$data.lastName;
}
},
}
</script>
<template>
<div>
<my-comp :first-Name='firstName' :last-Name='lastName' @on-Click='mtdCalculateFullName'></my-comp>
</div>
<div>
<p>Full Name:</p><p>{{fullName}}</p>
</div>
</template>

No comments:

Post a Comment