vue 實(shí)現(xiàn)點(diǎn)擊空白處執(zhí)行方法(列表收回、隱藏等操作)

解決問(wèn)題:TreeSelect組件初次點(diǎn)擊面板消失
結(jié)合TreeSelect組件 alwaysOpen 屬性

<template>
    <div>
        <div class="show" v-show="show" v-clickoutside="handleClose">
            顯示
        </div>
    </div>
</template>
 
<script>
const clickoutside = {
    // 初始化指令
    bind(el, binding, vnode) {
        function documentHandler(e) {
            // 這里判斷點(diǎn)擊的元素是否是本身,是本身,則返回
            if (el.contains(e.target)) {
                return false;
            }
            // 判斷指令中是否綁定了函數(shù)
            if (binding.expression) {
                // 如果綁定了函數(shù) 則調(diào)用那個(gè)函數(shù),此處binding.value就是handleClose方法
                binding.value(e);
            }
        }
        // 給當(dāng)前元素綁定個(gè)私有變量,方便在unbind中可以解除事件監(jiān)聽(tīng)
        el.__vueClickOutside__ = documentHandler;
        document.addEventListener('click', documentHandler);
    },
    update() {},
    unbind(el, binding) {
        // 解除事件監(jiān)聽(tīng)
        document.removeEventListener('click', el.__vueClickOutside__);
        delete el.__vueClickOutside__;
    },
};
export default {
    name: 'HelloWorld',
    data() {
        return {
            show: true,
        };
    },
    directives: {clickoutside},
    methods: {
        handleClose(e) {
            this.show = false;
        },
    },
};
</script>
 
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.show {
    width: 100px;
    height: 100px;
    background-color: red;
}
</style>

參考文章:https://blog.csdn.net/heynewbie/article/details/106883412

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容