Writes a click-outside directive to trigger closing of context menu

This commit is contained in:
Alicia Sykes 2021-06-24 20:50:48 +01:00
parent c1a8f5c032
commit 318c2602a0
2 changed files with 43 additions and 4 deletions

View File

@ -7,16 +7,18 @@ import VSelect from 'vue-select'; // Select dropdown component
import VTabs from 'vue-material-tabs'; // Tab view component, used on the config page
import Toasted from 'vue-toasted'; // Toast component, used to show confirmation notifications
import { toastedOptions } from './utils/defaults';
import Dashy from './App.vue';
import router from './router';
import registerServiceWorker from './registerServiceWorker';
import { toastedOptions } from '@/utils/defaults';
import Dashy from '@/App.vue';
import router from '@/router';
import registerServiceWorker from '@/registerServiceWorker';
import clickOutside from '@/utils/ClickOutside';
Vue.use(VTooltip);
Vue.use(VModal);
Vue.use(VTabs);
Vue.use(Toasted, toastedOptions);
Vue.component('v-select', VSelect);
Vue.directive('clickOutside', clickOutside);
Vue.config.productionTip = false;

37
src/utils/ClickOutside.js Normal file
View File

@ -0,0 +1,37 @@
/**
* A simple Vue directive to trigger an event when the user
* clicks anywhere other than the specified element.
* Used to close context menu's popup menus and tips.
*/
const instances = [];
function onDocumentClick(e, el, fn) {
const { target } = e;
if (el !== target && !el.contains(target)) {
fn(e);
}
}
export default {
bind(element, binding) {
const el = element;
el.dataset.outsideClickIndex = instances.length;
const fn = binding.value;
const click = (e) => {
onDocumentClick(e, el, fn);
};
document.addEventListener('click', click);
document.addEventListener('touchstart', click);
instances.push(click);
},
unbind(el) {
if (!el.dataset) return;
const index = el.dataset.outsideClickIndex;
const handler = instances[index];
document.removeEventListener('click', handler);
instances.splice(index, 1);
},
};