简体   繁体   English

在 vuejs 中将方法从子组件传递给父组件

[英]Pass method from child component to parent component in vuejs

Can someone help me with passing a function from the child component to the parent component?有人可以帮我将 function 从子组件传递到父组件吗? I am calling a modal in parent component.我在父组件中调用模态。 Inside component there are two buttons cancel and submit.组件内部有两个按钮取消和提交。 I want to close the child component after clicking on the submit or cancel buttons.单击提交或取消按钮后,我想关闭子组件。 I tried to close the modal by declaring "show" in data, It makes the style display=None and makes the modal disappear but I am not able to scroll the screen after that.我试图通过在数据中声明“显示”来关闭模式,它使样式 display=None 并使模式消失,但之后我无法滚动屏幕。

Parent component父组件

<div>
  <modal-dialog v-if="show" id="showCommentEffortBox">
     <input type="button" value="Cancel" @click="show=false">
     <input type="button" value="Submit" @click="show=false">
  </modal-dialog>

data() {
     return {
        show: true
       }
    }

Child component子组件

<template>
    <transition name="modal">
        <div class="modal fade" tabindex="-1" data-backdrop="static" data-keyboard="false">
            <div class="modal-dialog" style="max-width: 95%">
                <div class="modal-content"  style="max-height: 90vh;">
                    <header class="modal-header">
                        <slot name="header">
                        </slot>
                    </header>
                    <section class="modal-body" style="overflow-y: auto">
                        <slot name="body">
                        </slot>
                    </section>
                </div>
            </div>
        </div>
    </transition>
    </template>

    <script>
    export default {
    *****
    }
    </script>

Thanks in Advance提前致谢

Have a look at these docs, this is the basic standard behaviour.看看这些文档,这是基本的标准行为。

https://v2.vuejs.org/v2/guide/components.html#Listening-to-Child-Components-Events https://v2.vuejs.org/v2/guide/components.html#Listening-to-Child-Components-Events

You can pass methods as you pass data through slots.您可以在通过槽传递数据时传递方法。

Child component子组件

<header class="modal-header">
  <slot name="header" :methodName="methodName">
  </slot>
</header>
<section class="modal-body" style="overflow-y: auto">
  <slot name="body" :methodName="methodName">
  </slot>
</section>

Parent Component父组件

<template #header="props">
{{ props.methodName() }}
</template>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM