我正在尝试从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>
这不起作用,因为在您检查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>