前言:开发中,有个组件需要点击某个按钮,按钮旁边出现一个小弹框;当用户再次点击按钮或其他区域关闭弹框,并无遮罩层,实现方法:

<template>
  <div ref="box">
    <button @click="popVisible = !popVisible">
      {{ popVisible ? "关闭" : "打开" }}
    </button>
    <div class="pop" v-show="popVisible"></div>
  </div>
</template>
<script>
export default {
  name: "MyDemo",
  data() {
    return {
      popVisible: false,
    };
  },
  mounted() {
    document.addEventListener("click", (e) => {
      if (!this.$refs.box.contains(e.target)) this.popVisible = false;
    });
  },
};
</script>

<style scoped>
.pop {
  width: 300px;
  height: 150px;
  background: #fff;
  box-shadow: 0 0 10px #ccc;
}
</style>

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐