Vue.js关闭来自子组件的模态

时间:2017-09-11 10:54:36

标签: vue.js vuejs2 vue-component

我想从这个模态中的子组件关闭vuejs模态。 情况下:

<modal name="some-modal">
        <some-component></some-component>
</modal>

在SomeComponent中我想关闭some-modal。 这是好方法吗?可以做得更好吗?请adivse, 此致

4 个答案:

答案 0 :(得分:2)

您需要使用this.$emit('exit', true)从子组件中发出事件。

然后在父组件(模态)中侦听该事件。

<modal name="some-modal">
    <some-component @exit="closeModal"></some-component>
</modal>

然后将逻辑写入closeModal函数。

答案 1 :(得分:0)

当然没问题。您可以使用Vue的自定义事件系统:

https://vuejs.org/v2/guide/components.html#Custom-Events

至于判断这是否是理想的方法,没有人可以告诉您提供的信息量最少。

答案 2 :(得分:0)

这是我自己制作的自定义模式,它使用插槽将内容推入其中。

myModal.vue


<template>
    <transition name="modal">
        <div class="modal-mask">
            <div class="modal-wrapper">
                <header class="modal-header header-toolbar">
                    <h3>
                        <span>{{modalTitle}}</span>
                    </h3>
                    <span class="icon">
                        <i class="fa fa-times" aria-hidden="true" @click="hideModal"></i>
                    </span>
                </header>
                <section class="modal-body">
                    <slot></slot>
                </section>
            </div>
        </div>
    </transition>
</template>

<script>
    export default {
        name: 'my-modal',
        props: {
            modalTitle: {
                type: String,
                default: null,
            },
        },
        methods: {
            hideModal() {
                this.$emit('hide');
            },
        },
    };
</script>

如何使用它:

<my-modal v-if="modalState" @hide="modalState = false">
            ...Content
</my-modal>

将数据中的modalState设置为false,或将其定义为prop或其他任何内容。 当你想要显示模态时,只需将其更改为true即可。如果你想要类定义,我也可以给你scss

答案 3 :(得分:0)

您可以使用作用域槽传递回调以关闭父模式,例如:

modal.vue

<template>
  <div>
    <slot :close="close">
    </slot>
  </div>
</template>

<script>
  export default {
    name: 'Modal',
    methods: {
      close() {
        // Whatever you do to close the modal
      }
    }
  }
</script>

现在您可以在插槽中使用它:

<modal name="some modal" v-slot="slotScope">
  <some-component @close="slotScope.close" />
</modal>

这样,每当您在“某些组件”中发出“关闭”事件时,都会触发“模态”组件中的关闭方法。

相关问题