In our project, we're utilizing vue and typescript, which means that our .vue files are structured very similarly to the layout outlined in this blogpost.
One of our child components is emitting a custom event called changeType
. I'd like to trigger a function on the parent component whenever this event is emitted.
childComponent.vue
<template>
<div>
<span @click="changeType('test')"></span>
</div>
</template>
<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
@Component
export default class ChildComponent extends Vue {
@Prop(
{
default: 'notTest',
validator: (type) => {
return [
'test',
'notTest',
].indexOf(type) > -1;
},
},
)
currentType!: string;
changeType(currentType = 'notTest') {
this.$emit('changeType', currentType);
}
}
</script>
Now, I'm faced with uncertainty about what to include in my parentComponent.vue file, where there's a <childComponent />
within the template
section.
The Vue documentation primarily covers handling child events using v-on
within the <template>
area:
<blog-post
...
v-on:enlarge-text="postFontSize += 0.1"
></blog-post>
Therefore, do I need something like this:
parentComponent.vue
<template>
<childComponent v-on:changeType="handleChangeType" />
</template>
Alternatively, is there a way to handle it solely within the <script>
tag? The use of class + typescript syntax has made researching solutions more challenging. I tried methods like this.$on
, but TypeScript didn't approve, leading me to wonder if it should be placed elsewhere in the class structure (like the constructor or similar).
Coming from a Backbone background, I was hoping for something akin to an onChangeType
method directly added to the parent component to automatically manage the event. However, it's possible that approach is outdated and newer techniques exist.
How can I effectively address a child component event within the parent component's tags in vue? Is it achievable without incorporating v-on
in the template? Am I misunderstanding the correct implementation method?