如何检测元素外部的点击?我正在使用Vue.js,因此它将不在我的模板元素之外。我知道如何在Vanilla JS中做到这一点,但是当我使用Vue.js时,我不确定是否有更合适的方法来做到这一点?
这是Vanilla JS的解决方案:div外部的Javascript Detect Click事件
我想我可以使用更好的方法来访问元素?
如何检测元素外部的点击?我正在使用Vue.js,因此它将不在我的模板元素之外。我知道如何在Vanilla JS中做到这一点,但是当我使用Vue.js时,我不确定是否有更合适的方法来做到这一点?
这是Vanilla JS的解决方案:div外部的Javascript Detect Click事件
我想我可以使用更好的方法来访问元素?
I create a div at the end of the body like that:
<div v-if="isPopup" class="outside" v-on:click="away()"></div>
Where .outside is :
.outside {
width: 100vw;
height: 100vh;
position: fixed;
top: 0px;
left: 0px;
}
And away() is a method in Vue instance :
away() {
this.isPopup = false;
}
Easy, works well.
There are already many answers to this question, and most of them are based on the similar custom directive idea. The problem with this approach is that one have to pass a method function to the directive, and cannot directly write code as in other events.
I created a new package vue-on-clickout
that is different. Check it out at:
It allows one to write v-on:clickout
just like any other events. For example, you can write
<div v-on:clickout="myField=value" v-on:click="myField=otherValue">...</div>
and it works.
You can register two event listeners for click event like this
document.getElementById("some-area")
.addEventListener("click", function(e){
alert("You clicked on the area!");
e.stopPropagation();// this will stop propagation of this event to upper level
}
);
document.body.addEventListener("click",
function(e) {
alert("You clicked outside the area!");
}
);
社区中有两个软件包可用于此任务(均已维护):
If you have a component with multiple elements inside of the root element you can use this It just works™ solution with a boolean.