vue禁止鼠标滚轮事件(禁止弹窗后面的遮罩层下的背景滚动)

代码如下

原理: 监听visible的变化,然后通过禁止、解除鼠标滚轮事件来禁止背景滚动

<<template>
		<div class="dialog-wrapper" v-show="visible" @click.self="close">
				<div class="dialog target">
					<slot></slot>
				</div>
		</div>
</template>

<script>
  export default {
    name: "ModalDialog",
    props: {
      visible: {
        type: Boolean,
        default: false
      }
    },
    watch: {
      visible: {
        handler(newVal) {
          if(!newVal) {
            // 解除禁止滚动
	          this.$nextTick(() => {
              document.removeEventListener('mousewheel', this.mousewheelHandler, {passive: false})
            })

            this.$emit('update:visible', false)
          } else {
            this.$emit('update:visible', true)
            // 每次弹出弹窗,让遮罩层下面的页面不能滚动
            this.$nextTick(() => {
              document.addEventListener('mousewheel', this.mousewheelHandler, {passive: false})
            })
          }
        },
        immediate: true
      }
    },
    methods: {
      mousewheelHandler (e) {
        e.preventDefault()
      },
      close() {
        this.$emit('update:visible', false)
      }
    },
  }
</script>

<style lang="scss" scoped>
	.dialog-wrapper {
		position: fixed;
		top: 0;
		left: 0;
		bottom: 0;
		right: 0;
		background-color: rgba(0,0,0,.4);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 999;
		.dialog {
			box-sizing: border-box;
			padding: 15px;
			background-color: #fff;
			border-radius: 4px;
		}
	}
</style>


Logo

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

更多推荐