当我尝试Vue.js自定义指令时,我尝试创建搜索内的下拉菜单时,我很难受。我不知道如何检测孩子们的点击情况
<div v-dropdown-directive class="dropdown">
<div class="title">This is dropdown title</div>
<div class="close">Close dropdown</div>
</div>
指令
import Vue from 'vue'
Vue.directive('dropdown-directive', {
bind (el) {
el.event = (e) => {
if (el === e.target) {
console.log('parent clicked')
el.classList.add('open') // this will add class open to parent, so dropdown will open
} else if (el.contains(e.target)) {
console.log('children clicked')
// this is working, but when I click on children has class "title" i'ts also working,
// I want only work when I click on children contain class "close"
} else if (!el.contains(e.target)) {
console.log('detect click outside')
el.classList.remove('open')
}
}
}
})
在下面的片段中,如果你点击红色,那就是父元素。
Vue.directive('DropdownDirective', {
bind(el, binding) {
let type = binding.arg;
const clickFunction = (e) => {
if (e.target.classList.contains('close')) {
console.log('close')
} else if (e.target.classList.contains('title')) {
console.log('title:', e.target.textContent)
} else if (e.target === el) {
console.log('parent')
} else {
console.log('outside')
}
}
// adding a general eventListener, so you can check for clicks outside
window.addEventListener(type, clickFunction);
}
})
new Vue({
el: "#app"
})
.dd-item {
width: 50%;
background: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-dropdown-directive:click class="dropdown" style="background-color:red;">
<div class="title dd-item">This is dropdown title</div>
<div class="close dd-item">Close dropdown</div>
</div>
</div>
重点是,你必须定义你想监听的事件。
:click
),并将该参数用在绑定了eventListener
更多关于 Vue 指令。https:/vuejs.orgv2guidecustom-directive.html。