備注:20190717
這個方法目前發現是有問題的,我在做新的vue的項目時,發現這個方案是有問題的,在前一個項目時沒有問題,現在的這段時間的這個項目有問題:
1.實現不了點擊一個按鈕彈出一個彈框,點擊彈框外的位置關閉彈框的需求,究其原因,就是點擊按鈕的時候就相當於點擊了彈框外的地方,找到原因后,就可以快速廢棄這個方法。
2.擴展,實現不了
正確解決方案:請點擊:
https://www.cnblogs.com/DZzzz/p/11204805.html
在寫vue的項目的時候,彈框經常性出現,並要求點擊彈框外面,關閉彈框,那么如何實現呢?且聽我一一。。。不了,能實現效果就好
<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); }, 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>
就是方便你們拷貝的。
思路:
我最初的應對思路是給彈框的其余區域加點擊事件,點擊之后關閉彈框,用了百分比布局。(當然low爆了)。
時間充裕的時候,就研究使用了這種方法,是否更高級呢,反正我覺得方便多了啊
簡單介紹用到了的兩個vue指令
bind:只調用一次,指令第一次綁定到元素時調用。在這里可以進行一次性的初始化設置。
unbind:只調用一次,指令與元素解綁時調用。