簡單想應該怎麼實現? 一、確定是給document增長一個click事件監聽 二、當發生click事件的時候判斷是否點擊的當前對象 結合着本思路和指令我們來實現。vue
一個指令定義對象能夠提供以下幾個鉤子函數 (均爲可選):node
bind
:只調用一次,指令第一次綁定到元素時調用。在這裏能夠進行一次性的初始化設置。inserted
:被綁定元素插入父節點時調用 (僅保證父節點存在,但不必定已被插入文檔中)。update
:所在組件的 VNode 更新時調用,可是可能發生在其子 VNode 更新以前。指令的值可能發生了改變,也可能沒有。可是你能夠經過比較更新先後的值來忽略沒必要要的模板更新 (詳細的鉤子函數參數見下)。componentUpdated
:指令所在組件的 VNode 及其子 VNode 所有更新後調用。unbind
:只調用一次,指令與元素解綁時調用。接下來咱們來看一下鉤子函數的參數 (即 el、binding、vnode 和 oldVnode)。 express
建立指令對象,分析放在代碼中bash
<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>
複製代碼
注:指令代碼參考自iview 原創文章,轉載請註明出處iview