简体   繁体   English

在可重用的 vue 组件中注册的事件不起作用

[英]Events registered in reusable vue components not working

On the site I'm working on, I repeatedly use components such as buttons and dropdowns.在我正在开发的网站上,我反复使用按钮和下拉菜单等组件。 Because I use them so often I've decided to create a custom component for particular features so that I don't have to redeclare styling.因为我经常使用它们,所以我决定为特定功能创建一个自定义组件,这样我就不必重新声明样式。 One such component is: BlueButton.vue一个这样的组件是:BlueButton.vue

<template>
    <v-btn dark color="blue" class="blue-btn">
        <slot>
            <!--  -->
        </slot>
    </v-btn>
</template>

I'm then trying to use this component inside a form component called TheForm.vue:然后我尝试在名为 TheForm.vue 的表单组件中使用这个组件:

<template>
    <blue-button @click="showTheDialog = false" v-if="thebutton(btn)">Cancel</blue-button>
</template>
<script>
import BlueButton from '../components/BlueButton'

export default {

    props: {
        //
    },

    components: {
        'blue-button' : BlueButton
    },
</script>

However, although the button inside of TheForm.vue is styled correctly, events such as @click and v-if aren't registering (ie I can click the button but it won't do anything - It won't even show an error).然而,尽管 TheForm.vue 中的按钮样式正确,但 @click 和 v-if 等事件没有注册(即我可以单击按钮但它不会做任何事情 - 它甚至不会显示错误)。

How can I fix this so that props and events work?我该如何解决这个问题,以便道具和事件起作用?

Events won't automatically propagate up when you wrap a component.包装组件时,事件不会自动向上传播。

You'd either need to pass them on individually, something like this:您需要单独传递它们,如下所示:

<v-btn dark color="blue" class="blue-btn" @click="$emit('click', $event)">

Or you can pass on all events like this:或者你可以像这样传递所有事件:

<v-btn dark color="blue" class="blue-btn" v-on="$listeners">

See:看:

https://v2.vuejs.org/v2/api/#vm-listeners https://v2.vuejs.org/v2/api/#vm-listeners

The v-if directive should be working correctly. v-if指令应该可以正常工作。 You don't need to do anything special to get that to work.你不需要做任何特别的事情来让它工作。

If you need to pass props it's much the same as with events.如果您需要传递道具,则与事件大致相同。 You either need to pass them on individually or all together.您需要单独或一起传递它们。 To pass them all together it'd be:要将它们一起传递,它将是:

<v-btn dark color="blue" class="blue-btn" v-bind="$attrs">

Note that $attrs will only contain attributes that are not defined as props, so for any that you do define as props you'll need to pass those separately.请注意, $attrs将仅包含未定义为 props 的属性,因此对于您定义为 props 的任何属性,您都需要单独传递它们。

See:看:

https://v2.vuejs.org/v2/api/#vm-attrs https://v2.vuejs.org/v2/api/#vm-attrs

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

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