vue-js click outside function也可以在我的元素内部使用-如何修复

问题描述 投票:0回答:1

我正在尝试从vuetify识别我的元素之外的单击,该元素是快速拨号项。为了做到这一点,我正在使用此解决方案中的指令来解决我的问题[Detect click outside element。我可以单击外部并获取日志进行验证,但是每当我在元素内部单击时,我也都会获得日志“单击外部”。如何防止指令也单击元素的内部?我确实有日志语句可以检查何时触发外部点击。我尝试停止事件冒泡或事件传播,以防与之相关,但这无济于事。谢谢!

<template>
    <v-card>
        <v-speed-dial
            v-click_outside="outside"
            :bottom="true"
            :right="true"
            :direction="direction"
            :transition="transition"
            fixed
        >
        <template v-slot:activator>
            <v-btn
                :class="{ is_active: isActive }"
                color="red"
                fab
                @click="toggleButton"
                dark
                x-large
            > 
                <span  v-if="isActive"><v-icon>mdi-pencil</v-icon></span>
                <v-icon v-else>mdi-plus </v-icon>
            </v-btn>
        </template>
            <v-btn 
                fab 
                dark 
                large 
                color="white" 
                @click.stop="$emit('scrollTo')">
                <v-icon color="#F0BE85">mdi-delete</v-icon>
            </v-btn>
        </v-speed-dial>
    </v-card>
</template>

<script>

export default {
name: 'FloatingButton',
props: {
    display: Boolean,
    ott: Boolean,
    preroll: Boolean,
    gt: Boolean
},
data: () => ({
    direction: 'top',
    fab: false,
    right: true,
    bottom: true,
    transition: 'scale-transition',
    isActive: false,
    backgroundColor: false
}),
methods: {
    toggleButton: function () {
    this.isActive = !this.isActive
    this.backgroundColor = !this.backgroundColor
    },
    outside:function(){
        console.log('clicked outside')
    }
},
directives: {
click_outside:{
    bind:function(el,binding,vnode){
        el.clickOutsideEvent=function(event){
            if (!(el == event.target || el.contains(event.target))) {
                    vnode.context[binding.expression](event);
            }
        }
        document.body.addEventListener('click',el.clickOutsideEvent)
    }
},
unbind:function(el){
    document.body.removeEventListener('click',el.clickOutsideEvent)
}
}
}
</script>
javascript vue.js dom vuetify.js
1个回答
0
投票

这不起作用,因为在您检查el.contains()时,该事件所针对的“加号”或“铅笔”图标不再存在,因为v-if将该元素切换为另一个。

相反,使用此元素使元素保持不变:

<v-btn :class="{ is_active: isActive }" color="red" fab @click="toggleButton" dark x-large>
  <v-icon>{{ isActive ? 'mdi-pencil' : 'mdi-plus' }}</v-icon>
</v-btn>
© www.soinside.com 2019 - 2024. All rights reserved.