问题
I know its not advised to pass function as a prop to the child component in Vue. But if I were to do it, how is that possible? This is what I have tried till now -
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, I'm calling show_divs($event), hide_divs($event) and other functions as you can see. Script is :-
<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());
}
}
Parent component template is:-
<ResultShowcase
:updateOnResize="updateOnResize"
:show_divs="show_divs"
:hide_divs="hide_divs"
:find_cordinates="find_cordinates"
:divsToBeRendered="divsToBeRendered"
>
</ResultShowcase>
These functions are working fine in the parent component. What am I doing wrong here? Also in the child component on mount I have tried to run the "show_divs()" but it doesnt get executed. Any help is highly appreciated.
回答1:
You could emit an event from the child component and run it inside the parent one :
@mouseover="$emit('show_divs',$event)"
in the parent component :
v-on:show_divs="show_divs"
method :
methods:{
show_divs(event){
console.log(event)
}
}
来源:https://stackoverflow.com/questions/61029499/how-to-pass-function-as-a-prop-to-child-component-and-call-it-from-there-in-vue