+
95
-

如何实现vue点击其他地方隐藏div

vue

请问如何实现vue点击其他地方隐藏div

网友回复

+
15
-

1、原生方法

js的contains方法用来查看dom元素的包含关系

<div id="box" style="width:110px;height:110px;background-color:red"></div>

<script type="text/javascript">
    document.addEventListener('click', (e)=> {
        var box = document.getElementById('box');
        if (box.contains(e.target)) {
            alert('点在内');
        } else {
            alert('点在外');
        }
    })
</script>

2、 vue 写法

ref是vue获取DOM元素的方法,在标签上绑定ref属性,js在组件内部用this.$refs.ref的值,调用。

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>BFW NEW PAGE</title>

    <script id="bfwone" data="dep=vue.2.2.min&err=0" type="text/javascript" src="http://repo.bfw.wiki/bfwrepo/js/bfwone.js"></script>
    <script type="text/javascript">
        bready(function() {
            var app = new Vue({
                el: '#app',
                data: {
                    isshow: true
                },
                created() {
                    document.addEventListener('click', (e)=> {
                        //console.log(this.$refs.box);
                        if (!this.$refs.box.contains(e.target)) {
                            this.isshow = false;
                        }
                    })
                }

            });
        });
    </script>
    <style>
    </style>
</head>
<body>
    <div id="app">
        <div id="box" ref="box" v-sh...

点击查看剩余70%

我知道答案,我要回答