如何将函数作为道具传递给子组件并在Vue中从那里调用它?
Posted
技术标签:
【中文标题】如何将函数作为道具传递给子组件并在Vue中从那里调用它?【英文标题】:How to pass function as a prop to child component and call it from there in Vue? 【发布时间】:2020-07-16 15:54:13 【问题描述】:我知道不建议将函数作为道具传递给 Vue 中的子组件。但如果我要这样做,那怎么可能呢?这是我到目前为止所尝试的 -
我的子组件 -
<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 @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>
在这里,我调用了 show_divs($event)、hide_divs($event) 和其他你可以看到的函数。脚本是:-
<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());
父组件模板是:-
<ResultShowcase
:updateOnResize="updateOnResize"
:show_divs="show_divs"
:hide_divs="hide_divs"
:find_cordinates="find_cordinates"
:divsToBeRendered="divsToBeRendered"
>
</ResultShowcase>
这些功能在父组件中运行良好。我在这里做错了什么?同样在挂载的子组件中,我尝试运行“show_divs()”,但它没有被执行。非常感谢任何帮助。
【问题讨论】:
【参考方案1】:您可以从子组件发出一个事件并在父组件中运行它:
@mouseover="$emit('show_divs',$event)"
在父组件中:
v-on:show_divs="show_divs"
方法:
methods:
show_divs(event)
console.log(event)
【讨论】:
以上是关于如何将函数作为道具传递给子组件并在Vue中从那里调用它?的主要内容,如果未能解决你的问题,请参考以下文章