vue中点击一个盒子显示样式,现在要点击盒子之外的空白处,让样式隐藏
时间: 2024-03-16 16:40:59 浏览: 16
这个需求可以通过监听页面点击事件来实现。具体实现步骤:
1. 给整个页面添加一个点击事件监听器,监听点击事件。
2. 在盒子显示时,阻止点击事件冒泡,即点击盒子时,不触发页面点击事件。
3. 在盒子外部点击时,隐藏盒子,并移除页面点击事件监听器。
下面是一个可能的实现代码,仅供参考:
```
<template>
<div ref="box" class="box" :class="{active: showBox}" @click.stop="showBox = true">
点我显示样式
</div>
</template>
<script>
export default {
data() {
return {
showBox: false
}
},
mounted() {
document.addEventListener('click', this.hideBox)
},
beforeDestroy() {
document.removeEventListener('click', this.hideBox)
},
methods: {
hideBox(e) {
if (this.showBox && !this.$refs.box.contains(e.target)) {
this.showBox = false
}
}
}
}
</script>
<style>
.box {
width: 100px;
height: 100px;
background-color: #ccc;
}
.box.active {
color: red;
}
</style>
```