请教一下VUE2的事件问题

// 子组件 alert.vue

<template>
<div class="alert" v-if="show" @click="close">
    <slot></slot>
</div>
</template>

<script>
export default{
    data: () => ({
        show: true
    }),
    methods: {
        close (e) {
            this.$emit('change', e)
            this.show = false // 如何阻止此处触发?
        }
    }
}
</script>

// 父组件 app.vue

<template>
    <alert @change="handle">消息提示</alert>
</template>

<script>
export default{
    methods: {
        handle (e) {
            console.log(e)
            // 此处 ??
        }
    }
}
</script>

我想要的效果是,可以在父组件中可以阻止子组件内的事件触发?
不知道这样可不可以做到?

阅读 4.5k
1 个回答

试试这样:

# Child

export default {
    props: {
        canClose: {
            type: Function,
            default: () => () => true
        },
    methods: {
        close () {
            if (this.canClose()) {
                // close
            }
        }
    }
}
# Parent
<template>
    <alert @change="handle" :can-close="canClose">消息提示</alert>
</template>

<script>
export default {
    methods: {
        canClose () {
            return false;
        }
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题