簡單想應該怎么實現?
1、肯定是給document增加一個click事件監聽
2、當發生click事件的時候判斷是否點擊的當前對象
結合著本思路和指令咱們來實現。
簡單介紹vue指令
一個指令定義對象可以提供如下幾個鉤子函數 (均為可選):
接下來我們來看一下鉤子函數的參數 (即 el、binding、vnode 和 oldVnode)。

代碼實現
創建指令對象,分析放在代碼中
<template> <div> <div class="show" v-show="show" v-clickoutside="handleClose"> 顯示 </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); }, update() {}, 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; }, },};</script><!-- Add "scoped" attribute to limit CSS to this component only --><style scoped>.show { width: 100px; height: 100px; background-color: red;}</style>以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答