请打开https://jsfiddle.net/gfmyt9u8/31/
当用户在<section>
标签区域之外单击时,应关闭打开的div覆盖面板。
产生场景的步骤:
实际结果:重叠面板未关闭
预期结果:在“蓝色边框div”和“打开覆盖面板”之外单击时,覆盖面板应关闭 在下面”
答案 0 :(得分:1)
使用mounted
生命周期钩子添加click事件侦听器,以检查click事件是否在元素外部,并基于该元素隐藏元素。
工作示例:
new Vue({
el: '#app',
data: {
displayList: false,
cat: ['A', 'B']
},
methods: {
itemSelect(o) {
this.displayList = false;
}
},
mounted: function () {
// Listen to all clicks on the document
document.addEventListener("click", function(event) {
// If the click inside the element, do nothing
if (event.target.closest(".section-main")) return;
// If the clicks outside the element, hide it!
this.displayList = false;
}.bind(this));
}
});
.display-no-selected {
cursor: text;
width: 300px;
height: 25px;
border: solid 2px blue;
}
.display-list {
border: solid 1px wheat;
width: 300px;
max-height: 150px;
overflow-y: auto;
}
.toggle-list {
display: none;
}
ul, .selected-ul {
list-style-type: none;
margin: 0;
padding: 0;
}
ul.inner-ul li {
cursor: pointer;
font-weight: normal;
}
ul.inner-ul li:hover {
background-color: wheat;
}
.default-highlight {
background-color: wheat;
}
ul.inner-ul li span {
margin-left: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<section class="section-main">
<div class="display-no-selected" @click="displayList=true"> Please Select Options
</div>
<div class="display-list"
v-bind:class="{'toggle-list': !displayList}">
<ul class="inner-first-ul inner-ul">
<li v-for="o in cat" @click="itemSelect(o)">
<span>{{o}}</span>
</li>
</ul>
</div>
</section>
</div>