Within this context, the parent element is transmitting the name
and age
props to the child component. The child then emits a customized event called changeAgeFn
which transfers its changeAge
method back to the parent.
In the parent component, the passed changeAge
event is linked to the click action on the button[change age]
.
Despite this approach not functioning as intended, I am eager to discover the proper or recommended procedure for executing events in a child component from its parent.
Parent.vue
<template>
<div class="parent-wrap">
<p>UserName: {{user}}, age: {{age}}
<button @click="changeAge()"> Change Age</button></p>
<child :user="user" :age="age" @userChanged="user = $event" @changeAgeFn="$event" ></child>
</div>
</template>
<script>
import child from './child.vue'
export default {
data: function() {
return {
user: 'John',
age: 35
}
},
components: {
child
},
}
</script>
<style>
.child-wrap {
border: 3px solid #000;
max-width: 300px;
padding: 20px;
background: lightblue;
}
.parent-wrap {
padding: 30px;
background-color: lightcoral;
border: 3px solid #000;
}
</style>
child.vue
<template>
<div class="child-wrap">
<p>UserName: {{user}}, age: {{age}}
<button @click="changeName"> Change Name</button></p>
</div>
</template>
<script>
export default {
props: ['user', 'age'],
methods: {
changeName() {
this.user = 'Rahul'
this.$emit('userChanged', this.user)
this.$emit('changeAgeFn', this.changeAge)
},
changeAge() {
this.age = '20'
}
}
}
</script>
Many thanks!