vue.js 如何绑定点击空白部分某个div隐藏

页面左侧有一个按钮,点击后划出一个面板,当用户点击页面空白处时,面板关闭,怎么绑定用户点击空白处这个事件呢

阅读 10.5k
5 个回答
<button @click="togglePanel">点击</buttton> 
<div v-show="visible" ref="main">弹出层</div>
export default {
    data () {
        return {
            visible: false
        }
    },
    methods: {
        togglePanel () {
            this.visible ? this.hide() : this.show()
        },
        show () {
            this.visible = true
            document.addEventListener('click', this.hidePanel, false)
        },
    
        hide () {
            this.visible = false
            document.removeEventListener('click', this.hidePanel, false)
        },
    
        hidePanel (e) {
            if (!this.$refs.main.contains(e.target)) {
                this.hide()
            }
        }
    },
    beforeDestroy () {
        this.hide()
    }
}

牛逼了,直接是请输入代码、、、

做个遮罩层,像弹出框那样,在遮罩层添加事件

新手上路,请多包涵

document 加事件判断 e.target

this.$refs.main.contains is not a function 为啥会出现这个

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题