1. 플러그인
[code]
export default ({ app }) => {
const Common = {
install: (Vue) => {
let handleOutsideClick
Vue.directive(‘closable’, {
bind(el, binding, vnode) {
handleOutsideClick = (e) => {
e.stopPropagation()
const { handler, exclude } = binding.value
let clickedOnExcludedEl = false
exclude.forEach((refName) => {
if (!clickedOnExcludedEl) {
const excludedEl = vnode.context.$refs[refName]
clickedOnExcludedEl = excludedEl.contains(e.target)
}
})
if (!el.contains(e.target) && !clickedOnExcludedEl) {
vnode.context[handler]()
}
}
document.addEventListener(‘click’, handleOutsideClick)
document.addEventListener(‘touchstart’, handleOutsideClick)
},
unbind() {
document.removeEventListener(‘click’, handleOutsideClick)
document.removeEventListener(‘touchstart’, handleOutsideClick)
},
})
},
}
})
[/code]
2. 사용하는 곳
[code]
exclude: 이벤트에서 제외될 ref (여기서는 자기자신)
handler: 이벤트 발생시 실행될 함수
<template>
<div
ref=”mydropdown”
v-closable=”{
exclude: [‘mydropdown’],
handler: ‘hideMenu’,
}”
>
<div><button @click=”toggleMenu”>메뉴</button></div>
<!– 팝업 레이어 –>
<div v-if=”showList”>
…
</div>
</div>
</template>
<script>
export default {
data() {
return {
showList: false,
}
},
methods: {
toggleMenu() {
this.showList = !this.showList
},
hideMenu() {
this.showList = false
}
}
}
</script>
[/code]