赞
踩
如下图,点击空白区域,只会触发html的默认事件
在main.js中,进行全局注册自定义指令
Vue.directive(‘click-outside’, {
bind: function (el, binding, vnode) {
el.clickOutsideEvent = function (event) {
// here I check that click was outside the el and his childrens
if (!(el == event.target || el.contains(event.target))) {
// and if it did, call method provided in attribute value
vnode.contextbinding.expression
}
}
document.body.addEventListener(‘click’, el.clickOutsideEvent)
},
unbind: function (el) {
document.body.removeEventListener(‘click’, el.clickOutsideEvent)
}
})
在需要引用的组件上进行“ref”注册
ref 被用来给DOM元素或子组件注册引用信息。引用信息会根据父组件的 $refs 对象进行注册。如果在普通的DOM元素上使用,引用信息就是元素; 如果用在子组件上,引用信息就是组件实例;
<elSelect ref="upSelect" ></elSelect>
3.添加自定义方法“v-click-outside”,其中 “this.$refs.upSelect.blur()” 的“upSelect”即为注册的ref
<elSelect
ref="upSelect"
v-click-outside="clickOutSide >
</elSelect>"
<script>
methods: {
clickOutSide() {
this.$refs.upSelect.blur();
},
}
</script>
效果如下
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。