HTML页<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Document</title><style type="text/css"> [v-cloak]{ display: none; }</style></head><body><div id="app" v-cloak> <div class="main" v-clickoutside="handleClose"> <button @click="show =!show">点击显示下拉菜单</button> <div class="dropdown" v-show="show"> <p>下拉框内容点击外侧区域可关闭</p> </div> </div> </div><script type="text/javascript" src="./vue.js"></script><script type="text/javascript" src="./index.js"></script><script type="text/javascript" src="chickoutside.js"></script></body></html>index页var app =new Vue({ el:'#app', data: { show:false }, methods:{ handleClose:function(){ this.show=false; } }});clickoutside页Vue.directive('clickoutside',{ bind:function(el,binding,vnode){ function documentHandler (e){ if (el.contains(e.target)) { return false; } if (binding.expression) { binding.value(e); } } el._vueClickOutside_=documentHandler; document.addEventListener('click',documentHandler); }, unbind:function(el,binding){ document.removeEventListener('click',el._vueClickOutside_); delete el._vueClickOutside_; }});
1 回答
pardon110
TA贡献1038条经验 获得超227个赞
全局自定义指令,书写位置需要在vue实例创建之前使用。换句话来讲,Vue.directive(...)部分,你应该写在new Vue 代码之前。
添加回答
举报
0/150
提交
取消