当我尝试使用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')
}
}
}
})发布于 2020-05-06 20:03:08
在下面的片段中:
之外。
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)的一个参数,并在绑定指令关于Vue指令的更多信息:https://v2.vuejs.org/v2/guide/custom-directive.html
https://stackoverflow.com/questions/61639428
复制相似问题