Vue2.js:v-click-outside自定义指令和vue-click-outside监听鼠标点击元素外部区域事件
【摘要】
自定义指令 v-click-outside
文档
https://v2.cn.vuejs.org/v2/guide/custom-directive.html
v-click-outside 可...
自定义指令 v-click-outside
文档
v-click-outside 可以实现点击外部区域才触发事件
实现代码
<template>
<div class="TestClickOutside">
<div
class="TestClickOutside__inner"
v-click-outside="handleClickOutside"
></div>
</div>
</template>
<script>
// created at 2022-08-25
export default {
name: 'TestClickOutside',
props: {},
components: {},
data() {
return {}
},
directives: {
'click-outside': {
bind(el, binding, vnode) {
console.log('bind')
function eventHandler(e) {
if (el.contains(e.target)) {
return false
}
// 如果绑定的参数是函数,正常情况也应该是函数,执行
if (binding.value && typeof binding.value === 'function') {
binding.value(e)
}
}
// 用于销毁前注销事件监听
el.__click_outside__ = eventHandler
// 添加事件监听
document.addEventListener('click', eventHandler)
},
unbind(el, binding, vnode) {
console.log('unbind')
// 移除事件监听
document.removeEventListener('click', el.__click_outside__)
// 删除无用属性
delete el.__click_outside__
},
},
},
methods: {
handleClickOutside() {
console.log('handleClickOutside')
},
},
created() {},
}
</script>
<style lang="less"></style>
<style lang="less" scoped>
.TestClickOutside__inner {
width: 100px;
height: 100px;
background-color: #666666;
}
</style>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
vue-click-outside
文档
安装
$ npm install vue-click-outside
- 1
<template>
<div class="TestClickOutside">
<div
class="TestClickOutside__inner"
v-click-outside="handleClickOutside"
></div>
</div>
</template>
<script>
// created at 2022-08-25
import ClickOutside from 'vue-click-outside'
export default {
name: 'TestClickOutside',
props: {},
components: {},
data() {
return {}
},
directives: { ClickOutside },
computed: {},
methods: {
handleClickOutside() {
console.log('handleClickOutside')
},
},
created() {},
}
</script>
<style lang="less"></style>
<style lang="less" scoped>
.TestClickOutside__inner {
width: 100px;
height: 100px;
background-color: #666666;
}
</style>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
文章来源: pengshiyu.blog.csdn.net,作者:彭世瑜,版权归原作者所有,如需转载,请联系作者。
原文链接:pengshiyu.blog.csdn.net/article/details/126527277
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)