What is the best way to manage a custom child event that is triggered using this.$emit in a parent component, specifically within the <script> section of the .vue file?

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?

Answer №1

To attach an event listener to a child component, utilize the $on method, as you previously mentioned.

Start by including a ref for the child component in the template:

<childComponent ref="child"/>

Following that, within the mounted hook, insert your listener in this manner:

mounted() {
  this.$refs.child.$on('changeType', this.handleChangeType);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging Material UI and TypeScript for Effective Styling: Maximizing the Use of !

Currently, I am in the process of developing a React application and incorporating Material UI for my components. One query that has arisen is regarding how to apply an !important property to a style. My attempt at achieving this looked like: <Paper cl ...

Ways to show a child's component element within the parent container

Within my Angular 11 project, there exists a component that exhibits a child component containing assorted table filters: Parent Component <table-filters></table-filters> <table> ... </table> Child Component (table-filters) <f ...

Tips for Angular JS Single Page Applications: Implementing Angular Controllers to Invoke Angular Services

Currently, I'm in the process of building a Node.js Application using Angular.js and Express.js. My goal right now is to populate a list with customer names and addresses by using this code snippet: var mylist = new generic.list(); mylist.add({name ...

Stop HTML audio playback upon clicking on a specific element

I'm looking to add background music to my website with a twist - a music video that pops up when the play button is clicked. But, I need help figuring out how to pause the background music once the user hits play. Play Button HTML - The play button t ...

What is the most effective method to exhibit every element within a content wrapper at a specific interval of time?

I am looking for a way to display each div within the content-wrapper after a specific time interval. Currently, I am using individual classes like el1, el2, el3, ... to accomplish this task. However, when dealing with content-wrappers containing multipl ...

Can you extract information from the XML file and modify the anchor tags?

<description> <div class="field field-name-field-image field-type-image field-label- hidden"><div class="field- items"><div class="field-item even"><a href="/news/news/vg"> ...

Managing Autocomplete Functionality in React with Material-UI, Both with and without a Pre

I am in need of an Autocomplete feature that offers the following functionalities: If the initial value has an id greater than 0, then I want the autocomplete to default to the provided object. If the initial value has an id less than or equal to 0, then ...

Internet Explorer causing issues with Jasmine mocking ajax calls

Recently, I attempted to develop a spec that enables mocking out Ajax calls. The testing procedure functions seamlessly on browsers such as Chrome and Firefox; however, I encountered some difficulties while executing the test case on Internet Explorer (spe ...

Revamping the hyperlinks in my collapsible menu extension

Is there a way to modify the links in this accordion drop menu so that they lead to external HTML pages instead of specific areas on the same page? I've tried various methods but can't seem to achieve it without affecting the styles. Currently, i ...

angular $stateProvider behaving unexpectedly with routing

Within my main file titled index.html, I have incorporated the following basic markup... <body ng-app="starter" ng-controller="AppCtrl"> <div ui-view></div> </body> In my separate file called app.js, I am utilizing $stateProvi ...

Extracting information from a string with JSON in Javascript

Can you assist me? I have developed a web service that provides a clean string after clicking on the URL: { "PersonID": 125, "Title": "Security Officer", "Company": "TSA", "CellNum": "423-915-3224", "EmergencyPhone": "", "Email": " ...

Passing a JavaScript Object to an ASP.NET Handler

How can I send a JavaScript object to an ASP.NET Handler and extract its values? I have defined a complex type object as follows: function AccountObjCreate() { var AccountsView = {}; AccountsView.Username = null; AccountsView.Email = null; AccountsView.P ...

Navigate to the top of the page prior to updating the Link route in NextJS

Whenever I click on a link to navigate to a new page, the page loads and immediately scrolls to the top. I want to change this behavior so that the scroll resets to the top before the new page is rendered. You can observe this issue on . If you scroll do ...

substitute bullet point list item with new element

Assuming I have a list: <ul class="ul-1"> <li class="li-1">xx -1</li> <li class="li-2">xx -2</li> <li class="li-3">xx -3</li> </ul> Then I store it as: var list = $('.ul-1').html(); In ...

Assign variable data to properties within an immutable object within a React component

I have declared a Const in my config.service.ts file like this: export const mysettings={ userid:"12324", conf:{ sessionDuration:30, mac:"LON124" } } I am using this constant in various components. However, instead of hardcoding these val ...

When using React, I noticed that adding a new product causes its attributes to change after adding another product with different attributes on the same page

Imagine you are browsing the product page for a Nike T-shirt. You select black color and size S, adding it to your cart. The cart now shows 1 Nike T-SHIRT with attributes color: black, size: S. However, if you then switch to white color and size M on the ...

The Response.Write function is not functioning properly in the production environment

I have created a C# WebService (ASMX) with the code snippet below: if (!SomeValidation()) { //context.Response.ContentType = "application/json"; //context.Response.ContentType = "text/plain"; context.Response.ContentType = "application/text"; ...

Having trouble with importing a TypeScript class: encountering a "cannot resolve" error message

Could you lend me your expertise? I'm puzzled by this issue that seems to be quite simple and straightforward: export class Rectangle { height: number = 0 width: number = 0 constructor(height: number, width: number) { this. ...

The Next.js React framework seems to be having trouble reading user input from a

I'm encountering an issue when attempting to save form email/password registration using Next.js as it is throwing an error. import {useState} from 'react' type Props = { label: string placeholder?: string onChange: () => void na ...

Changing divider color in Material-UI with React

I need some assistance with changing the color of the divider component from the material ui framework. I have successfully changed colors for other components using the useStyles() method like this: const useStyles = makeStyles(theme => ({ textPad ...