在項目中每每會有這樣的需求: 彈出框(或Popover)在 show 後,點擊空白處能夠將其 hide。vue
針對此需求,整理了三種實現方式,你們按實際狀況選擇。node
固然,咱們作項目確定會用到 UI 框架,常見的 Element 中的組件提供了這樣的方法。可是,就算使用框架,有些時候仍是要用到的,好比:express
Element 中的 Popover,當咱們想使用手動方式(trigger 觸發方式爲 manual時)控制它的 show & hide 的時候,就要本身實現這個功能啦。markdown
<span ref="projectButton">
<el-popover v-model="visible" trigger="manual" placement="bottom" @show="show" @hide="hide">
<p>啦啦啦</p>
<el-button slot="reference" type="primary" @click="visible = !visible">show</el-button>
</el-popover>
</span>
data () {
return {
visible: false
}
},
methods: {
show () {
document.addEventListener('click', this.hidePanel, false)
},
hide () {
document.removeEventListener('click', this.hidePanel, false)
},
hidePanel (e) {
if (!this.$refs.projectButton.contains(e.target)) {
this.visible = false
this.hide()
}
}
}
複製代碼
上面就是在 Popover show 的時候監聽 document 的 click 事件,觸發進入 hidePanel 方法,判斷當前點擊的 el 是否在 Popover 內部,若是不在,則手動 hide Popover ,而且移除監聽事件。框架
這個仍是蠻好理解的,我使用的也是這種方式,由於個人項目中須要這種需求的不多(好吧,就一個地方),因此我採用了這種方式。ide
<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>複製代碼
上面這種是網上比較火的一種方式(實際我沒有測試過),其實思路仍是那個思路 (給document增長一個click事件監聽,當發生click事件的時候判斷是否點擊的當前對象,不是就隱藏),優勢就是能夠封裝成全局/局部的指令,可多處使用。函數
下面簡單介紹下 vue 指令一個指令定義對象能夠提供以下幾個鉤子函數 (均爲可選):測試
---this
<template>
<div>
<div class="mask" v-if="showModal" @click="showModal=false"></div>
<div class="pop" v-if="showModal">
<button @click="showModal=false" class="btn">點擊出現彈框</button>
</div>
<button @click="showModal=true" class="btn">點擊出現彈框</button>
</div>
</template>
<script>
export default {
data() {
return {
showModal: false
};
}
};
</script>
<style scoped>
.mask {
background-color: #000;
opacity: 0.3;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 1
}
.pop {
background-color: #fff;
position: fixed;
top: 100px;
left: 300px;
width: calc(100% - 600px);
height:calc(100% - 200px);
z-index: 2
}
.btn {
background-color: #fff;
border-radius: 4px;
border: 1px solid blue;
padding: 4px 12px;
}
</style>複製代碼
上面這個就是添加一個看不見的遮罩替代 document ,點擊遮罩就隱藏。可是要注意:mask(遮罩)層的層級(z-index)要比彈出的pop的層級低。spa