Vue一直有个问题就是,像JQuery这种处理下面这行代码的时候可以直接获取html,body之类的DOM对象.但是Vue的组件没办法这么做.
$('html').click(function() { $('.nav-dropdown').hide(); });
常见场景是,下图这样一个下拉框,要点击空白处去隐藏就非常难做.
解决方法就是,添加自定义指令
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.context[binding.expression](event); } }; document.addEventListener('click', el.clickOutsideEvent); }, unbind: function (el) { document.removeEventListener('click', el.clickOutsideEvent); }, });
使用方法v-click-outside=’closeEvent’
<ul class="nav-list" v-click-outside='closeEvent' v-show="showList"> <li v-for="item in menuList" :key="item.title" v-on:click="item.isShow = !item.isShow" > <router-link :to=item.href>{{item.title}}</router-link> <!-- 有子菜单的 --> <ul class="nav-dropdown" v-if="item.dropDown" v-show="item.isShow"> <li v-for="subTitle in item.dropDown" :key="subTitle.title"> <router-link :to=subTitle.href>{{subTitle.title}}</router-link> </li> </ul> </li> </ul>
—-
methods: { backHome: function () { this.$store.commit("viewState/updateView", "home"); }, closeEvent:function(event){ // console.log('close event called'); this.menuList.forEach(function(value,key,arr){ value.isShow=false; }); // this.showList=false; } }
类似这样.
还有就是使用插件,但是感觉略麻烦.而且其实一般不想引入太多包。管理起来好麻烦。
https://github.com/ndelvalle/v-click-outside