Unable to dispatch an event from a child component to a parent component in Vue.js

Within my parent component, I retrieve an array of strings from an API and pass it down to the child component. The child component then displays this data as a dropdown list. When an item is selected from the dropdown, I aim to assign it to a specific variable. I attempted to use $emit and $event following documentation guidelines, but unfortunately, it is not functioning as expected. Could someone take a look at my code and point out where I might be mistaken?

The Parent Component in App.vue

<template>
    <div id="app">
        <nlp-vision-catalog v-bind:cataloglist="catalogs"  v-on:listenClick="setcatalogselected($event)" ></nlp-vision-catalog>
    </div>
</template>

<script>
    import NlpVisionCatalog from './components/NlpVisionCatalog'
    import axios from 'axios'

    export default {
        name: 'App',
        components: {
            NlpVisionCatalog
        },
        data (){
            return {
            catalogs :[],
            catalog_selected : ""
        }
    },
    methods:{
        fetchcatalogs(){
                axios.get("http://localhost:5000/clients")
                .then((resp)=>{this.catalogs.push.apply(this.catalogs,
                   resp.data.response.results.client_name);
                }).catch((err)=>{
                    console.log(err);
                })
        },
        setcatalogselected(catalog){
        this.catalog_selected = catalog;
    )}
},
    created(){
        this.fetchcatalogs()
    }
}
</script>
<style></style>

The Child Component - NlpVisionCatalog.vue


<template>
<div>
    <h3>Select Catalog</h3>
    <select>
        <option v-for="item in cataloglist">
            <p v-on:click="emitbackthecatalog(item)"> {{ item }} </p>
        </option>
    </select>
</div>
</template>

<script>
export default{
    name : 'NlpVisionCatalog',
    props: ['cataloglist'],
    data (){
        return {
            comp: ""
        }
    },
    methods:{
        emitbackthecatalog(catalog_name){
            this.$emit('listenClick',catalog_name);
        }
    }
};
</script>

<style>
</style>

Any insights on where I might be making a mistake would be greatly appreciated. ps- http://localhost:5000/clients is the api that is running on my system.

Answer №1

Your child component select element is causing the issue

To resolve this, update your code to include the onChange function in the select element:

 <h3>Select Catalog</h3>
    <select v-model="selected" v-on:change="emitbackthecatalog(selected)">
        <option v-for="item in cataloglist" :value="item" :key="item">
           {{ item }}
        </option>
    </select>



data (){
    return {
        selected: ""
    }
  },
  methods:{
    emitbackthecatalog(catalog_name){
        this.$emit('listenclick',catalog_name);
    }
  }

In your parent component:

<nlp-vision-catalog v-bind:cataloglist="catalogs" v-on:listenclick="setcatalogselected($event)"></nlp-vision-catalog>

For a demonstration, please visit the following link.

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

Tips for enhancing the fluidity of animations after removing an item from a list

I'm working on a project where I have a list of elements that are removed with an animation when clicked. However, I noticed that when one element is removed, the rest of the elements just jump up instead of smoothly transitioning. Is there a way to m ...

JSON is throwing an error because a semi-colon is missing before a statement

I encountered a perplexing error despite receiving the correct response and being able to view the JSON content: Below is the request: $.ajax({ type: "GET", url: urlTwitter, contentType: "applic ...

webpackDevMiddleware does not automatically trigger a reload

Currently, I have implemented webpack dev middleware in my project like this: const compiledWebpack = webpack(config), app = express(), devMiddleware = webpackDevMiddleware(compiledWebpack, { historyApiFallbac ...

Eslint is not functioning properly on the local machine

Having trouble setting up eslint for my project. When I try to run eslint --init, I keep getting this error: /usr/lib/node_modules/eslint/lib/cli.js:18 let fs = require("fs"), ^^^ SyntaxError: Unexpected strict mode reserved word at exports.runInThis ...

Tips for incorporating an HTML file using ng-include in double curly brace syntax {{ }}

Here is the code snippet I am working with: <div ng-repeat="pTabs in child.productTabs" ng-click="toggleProductTab($index)" ng-if="productTabIsActive(pTabs, $index)"> <div ng-repeat="specs in pTab.additionalSpecs"> <p>{{spec ...

Pass the ID of a dynamic textbox element to a child window upon clicking a link

One of the challenges I'm facing involves a textbox labeled "Branch Code" that links a branch to a corporate card transaction. At times, there is a requirement to split a transaction among multiple branches. To facilitate this process, I am constructi ...

Optimal method for linking NodeJS and Angular in a seamless integration

I am currently working on developing a web application that integrates a Node server as the backend and Angular for the front end. At the moment, my application consists of two JavaScript files: server.js and controller.js. Below is the code snippet for ea ...

Explore the various timer functionalities available in Angular.js

I am working on a project that requires displaying two timers on a webpage, each with different start times. The first timer should only show for 5 seconds, and then after 10 seconds, the second timer should be displayed. I am new to Angular and have writ ...

Using Rails to Pass Front-End JavaScript Data from an External API to the Controller

I need to retrieve coordinates from an external API, specifically the Google Maps API, and then send it to my controller. However, I am encountering a 500 internal server error when using jQuery/Ajax for this task. Researching the issue online suggests tha ...

Is it possible to dynamically add plotLines to the xAxis using datetime in HighCharts?

Hey there! I've been playing around with adding plotlines in Highcharts and I'm loving it. It's really easy to define a date time on the xAxis for a plotline, like this: xAxis: { plotLines: [{ color: '#dadada', ...

Creating a consolidated HTML table by extracting and comparing data from various JSON files

Being new to JS and JSON, I am struggling to find a suitable solution that works for me. I have two distinct json files. The first one: players.json contains the following data: { "players": [ { "id": 109191123, "surnam ...

How can I dynamically assign @ViewChild('anchor_name') to a newly updated anchor element in Angular 2+?

Upon receiving an item through a GET request, I set the item_id upon subscription. In the HTML file, I create a div with an anchor id="{{this.item_id}}". However, I encountered the following error: FeedComponent.html:1 ERROR TypeError: Cannot read propert ...

Setting the initial viewer position in Panolens: A step-by-step guide

I've been working on setting the initial viewer position for panolens.js for a while now. Here's how the set-up looks: const panoPhoto1 = 'https://conceptcityiasi.ro/assets/images/tours/tip1/apartamente-noi-de-vanzare-iasi-dacia-1_camera-ti ...

Adapt the stylesheet for mobile devices using CSS

I am struggling with updating file paths in CSS depending on whether the end user is accessing my site from a PC or mobile device. Below is my CSS code, where I attempted to redirect users if they are on a handheld device: <link rel="stylesheet" type=" ...

Animation of active chat list items on Whatsapp

Has anyone figured out a simple method to create an animation like the one in Whatsapp? For example, when you are on a chat screen and go back to the chat list, have you noticed how an active element is briefly highlighted in gray (to indicate which chat ...

Switching from an AJAX GET request to a POST request involves updating the

I have been trying to figure out how to convert my AJAX GET query to POST by reading forums and searching on Google, but I am still confused. If someone could assist me with this, it would be greatly appreciated. Thank you! Here is the code snippet I am w ...

Looking for visible elements in WebDriverIO?

Currently, I am developing a test suite using WebDriverIO for a website with multiple duplicate elements that are selectively displayed based on user interaction... For example, the site may contain five buttons that each open a tooltip. These tooltips ar ...

Trouble with Material-UI's useMediaQuery not identifying the accurate breakpoint right away

While utilizing the MUI useMediaQuery hook in my React app, I encountered a bug that resulted in errors being thrown due to the initial failure of the hook to recognize the correct breakpoint. Eventually, the page re-renders and displays the correct value. ...

ReactJS state refuses to update

In my FreeCodeCamp leaderboard table, I have implemented functionality where clicking on the highlighted table header calls different URLs based on sorting criteria. The application either calls https://fcctop100.herokuapp.com/api/fccusers/top/recent or ht ...

Issues with tangents in three.js compared to the VertexTangentsHelper with problems on display

After enabling the "vertexTangentsHelper" feature in THREE.js, I've noticed that the tangents on various geometries appear to be incorrect. I'm questioning whether these tangents are being miscalculated (possibly due to my shader output) or if t ...