Guide to successfully passing a function as a prop to a child component and invoking it within Vue

Is it really not recommended to pass a function as a prop to a child component in Vue? If I were to attempt this, how could I achieve it? Here is my current approach:

Within my child component -

<template>
 <b-card :style="{'overflow-y': 'scroll', 'border-top': '0px', 'height': 'calc(100% - 53px)', 'border-top-left-radius': '0px', 'border-top-right-radius': '0px'}">                            
                                        <div class="img-magnifier-container" :style="{'position': 'relative'}">
                                            <b-img :id="('og' + curr_doc_num) + index_page" :src="pageImages[responseData[curr_doc_num-1]['page_nums'][index_page-1]-1].pageValue" fluid-grow alt="Fluid-grow image" @load="updateOnResize" >
                                            </b-img>

                                            <div 
                                                :key="j" 
                                                :id="(j)" 
                                                @mouseover="show_divs($event)"
                                                @mouseout="hide_divs($event)"
                                                v-bind:style="{
                                                    left: divKey['bbox']['left'] + 'px', position:'absolute', top:divKey['bbox']['top'] + 'px', height:divKey['bbox']['height'] + 'px', width: divKey['bbox']['width'] + 'px', 'border': divKey['border-width'] + 'px solid rgb(' + 
                                                divKey['color'][0] + ',' +  divKey['color'][1] + ',' + divKey['color'][2] + ')', 'pointer-events': divKey['pointer-events'], 'z-index': divKey['z-index'], 'cursor': 'pointer' }" 

                                                v-on:click="find_cordinates($event)" 
                                                v-for="(divKey, j) in divsToBeRendered" 
                                                />
                                        </div>
                                    <!-- </b-tab>
                                </template>
                            </b-tabs> -->
                        </b-card>
</template>

Here, the functions show_divs($event), hide_divs($event), and others are called as shown. The script is as follows:

<script lang="ts">
import { Component, Vue, Watch, Prop } from "vue-property-decorator";

@Component({
  components: {}
})
export default class Showcase extends Vue {

  @Prop() public show_divs: any;

  @Prop() public hide_divs: any;

  @Prop() public find_cordinates: any;

  @Prop() public divsToBeRendered: any;

  public mounted() {
    console.log("show", this.show_divs());
  }
}

The template of the parent component is as follows:

  <ResultShowcase

              :updateOnResize="updateOnResize"
              :show_divs="show_divs"
              :hide_divs="hide_divs"
              :find_cordinates="find_cordinates"
              :divsToBeRendered="divsToBeRendered"
              >

  </ResultShowcase>

These functions work correctly in the parent component. What could be the issue here? Additionally, why does the "show_divs()" function not execute in the child component on mount? Any assistance would be greatly appreciated.

Answer №1

If you want to trigger an event from the child component and handle it in the parent component, you can do so by using the following method:

 @mouseover="$emit('show_divs',$event)"

In the parent component, you need to listen for this event like this:

  v-on:show_divs="show_divs"

Then, create a method called 'show_divs' in your parent component to handle the event:

methods:{
  show_divs(event){
    console.log(event)
  }
}

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

Sending data to and retrieving data from a server

Just a quick query. I've been using ajax POST and GET methods to send JSON data to a server and then fetch it back. However, I'm facing some confusion while trying to extract JSON information from the GET call. getMessage = function(){ $.ajax ...

Attempting to create a JavaScript function that will show a JSON array when the next button is clicked

I am facing an issue with displaying a JSON array based on specific start and end indices. Even though I managed to display the entire array, the first button click does not seem to work as expected. Upon clicking the first button, an error message "this.d ...

Combining JSON fields and searching based on the combined value within MarkLogic

In the JSON format provided below, I have stored a person's first name and last name along with their nickname. { "Person": { "Records": [ { "nameType": "Primary", "firstName": "Sagar", "lastName" ...

Using Vue.js to sort through data, extracting the properties of an object

I'm currently facing an issue with a filtering system on my website that is built in Vue.js. The system filters properties based on "states", "cities", and "type". While the code works smoothly for states and types, it seems to stumble when dealing wi ...

Issue with Nuxt Static Site Generation: Missing content on page after changing routes

Upon switching routes in my full static NUXT application, I anticipated immediate loading of all content on the new page. However, I am noticing a slight delay between the route change and the appearance of each component, leading to layout shifts. Is thi ...

What is the process for setting up a vertical carousel in Bootstrap 5 with a stationary previous image?

Looking for assistance with my vertical carousel project. Is there a way to create a vertical carousel in bootstrap 5 with the previous image fixed? I found a slider on this website: zara.com/jp/en/ I want to maintain the previous image in a fixed posit ...

The jqueryMobile Dialog persistently opens during pageshow, despite having the cookie already set

My jQuery mobile dialog keeps opening every time the page is refreshed, despite having a cookie set to open it only once. I can't figure out why it's loading without any triggers. Any assistance would be greatly appreciated. JAVASCRIPT function ...

Retrieving text that has been HTML-escaped from a textarea using jQuery

Within my HTML file, I have a <textarea id="mytextarea"></textarea>. Suppose a user inputs the following text: <hello>, world! How can I retrieve res = "&lt;hello&gt;, world!"; based on the user's input? The current code s ...

Allow iframe to be edited within jsfiddle

I have a question that I need to ask soon, but first I need an editable iframe in jsfiddle. It's working fine on my local machine, but not on jsfiddle. I believe it's because of the frames being used? On my local machine, I use: setTimeout(&apo ...

The dom does not automatically update when data is modified inside the watch function

Here is the data within a component: data: function () { return { sltAreaStyle: { paddingTop: "3%", }, checkedTypes: ["krw", "btc", "usdt"], }; }, Next, we have the watch function for the checkedTypes d ...

Press the 'enter' button to post your tweet with Greasemonkey

I am working on a Greasemonkey script that will automatically submit a tweet when the user presses the 'enter' key. The script works perfectly on a basic HTML page with some help from tips I found on this website. However, when I attempt to use t ...

Tips for creating a breakpoint in Sass specifically for a 414px iPhone screen size

For my latest project, I am utilizing sass and looking to incorporate a sass breakpoint or media query. My goal is to have the code execute only if the screen size is 414px or less. Below is my existing code: @include media-breakpoint-down(sm) { .sub-men ...

Backend communication functions seamlessly within the service scope, yet encounters obstacles beyond the service boundaries

I'm facing an issue with accessing data from my backend. Although the service successfully retrieves and logs the data, when I try to use that service in a different module, it either shows "undefined" or "Observable". Does anyone have any suggestions ...

The form will only display results after the "Submit" button is clicked twice

Recently, I built a flask website where the form and results are displayed on the same page. However, there seems to be an issue that arises upon clicking the 'submit' button for the first time after running 'flask run'. The error messa ...

AngularJS modal not functioning properly after sending $http request

I have successfully implemented a pop-up modal in my Angular page using code from a reliable source. However, when I include a button for an HTTP request on the same page, the functionality of the AngularJS modal stops working after the HTTP request is mad ...

Why does the ReactJS MaterialUI Modal fail to update properly?

Recently, I encountered a curious issue with my Modal component: https://i.stack.imgur.com/dkj4Q.png When I open the dropdown and select a field, it updates the state of the Object but fails to render it in the UI. Strangely, if I perform the same action ...

Unexpected "<" and dual output in jade include seem to defy explanation

i am currently redesigning my website to incorporate dynamic includes. These includes are pre-rendered on the server and then passed to res.render() however, I am encountering unexpected occurrences of < and > on the page, along with the issue of th ...

The compilation of TypeScript and ES Modules is not supported in Firebase Functions

Recently, I integrated Firebase Functions into my project with the default settings, except for changing the value "main": "src/index.ts" in the package.json file because the default path was incorrect. Here is the code that was working: // index.ts cons ...

What could be the reason for angularjs not functioning as expected?

After attempting to create a basic JavaScript unit test using angular.js, I encountered failure without understanding the reason behind it. test.html <html> <head> <script src="angular-1.2.21/angular-scenario.js" ng-autotest></ ...

The issue of a non-functional grid with scroll in a flexbox

I've encountered a problem while working with the grid layout using divs and flexbox. The header, which I want to be fixed, is overlapping with the first row and I'm struggling to get the scrolling behavior right. How can I address this issue? I ...