vue中點擊空白處隱藏彈框(用指令優雅地實現)



<template>
    <div>
        <!-------  自定義指令,原來的click方法不影響使用 --------->
        <div class="show" v-show="show" v-clickoutside="handleClose" @click="showOrHide">
            顯示
        </div>
    </div>
</template>

<script>
const clickoutside = {
    // 初始化指令
    bind(el, binding, vnode) {
        function documentHandler(e) {
            // 這里判斷點擊的元素是否是本身,是本身,則返回
            if (el.contains(e.target)) {
                return false;
            }
            // 判斷指令中是否綁定了函數
            if (binding.expression) {
                // 如果綁定了函數 則調用那個函數,此處binding.value就是handleClose方法
                binding.value(e);
            }
        }
        // 給當前元素綁定個私有變量,方便在unbind中可以解除事件監聽
        el.__vueClickOutside__ = documentHandler;
        document.addEventListener('click', documentHandler);
    },
    unbind(el, binding) {
        // 解除事件監聽
        document.removeEventListener('click', el.__vueClickOutside__);
        delete el.__vueClickOutside__;
    },
};
export default {
    name: 'HelloWorld',
    data() {
        return {
            show: true,
        };
    },
    directives: {clickoutside},
    methods: {
        handleClose(e) {
            this.show = false;
        },
        showOrHide () {
             this.show = !this.show;
        }
    },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.show {
    width: 100px;
    height: 100px;
    background-color: red;
}
</style>

轉自https://www.cnblogs.com/DZzzz/p/9716408.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM