JAVASCRIPT
VUE
REACT
NODE
ES6
TYPESCRIPT

Vue点击元素之外隐藏该元素

2023. 05. 22    

vue点击元素之外隐藏该元素

vue点击元素之外隐藏该元素

<body>
    <div id="app" >
        <div class="showBox" ref="showBox" v-if="isShow"></div>
        <button v-outsild>点击</button>
    </div>
    <script>
        new Vue({
            el: '#app',
            data: function () {
                return {
                    isShow: true
                }
            },
            directives:{
                outsild:{
                    inserted(el){
                        document.addEventListener('click', function (event) {
                            if(!(el.contains(event.target))){
                                el.style.display = 'none'
                            }
                        })
                    },
                },
               
            },
            mounted() {
                let that = this;
                document.addEventListener('click', function (event) {
                    const div = that.$refs.showBox;
                    if (div) {
                        that.isShow = true
                        if (!(div.contains(event.target))) {  
                            that.isShow = false
                        }
                    }
                })
            },
            computed: {

            },
            created() {

            },
            methods: {
               
            }
        })

    </script>
</body>