UNPKG

@marlonwiss/vue-directives

Version:

A lightweight Vue 3 plugin providing a collection of custom directives to enhance your development experience.

92 lines (84 loc) 2.38 kB
import { nextTick } from 'vue'; const vFocus = { mounted: (el) => el.focus() }; const vBlur = { mounted: (el) => nextTick(() => el.blur()) }; const switchContext = /* @__PURE__ */ new WeakMap(); function getParentAndSwitchValue(el) { const parent = el.parentElement; if (!parent) { el.style.display = "none"; return; } const switchValue = switchContext.get(parent); return { parent, switchValue }; } const vSwitch = { created(el, binding) { switchContext.set(el, { value: binding.value, found: false }); }, updated(el, binding) { const prev = switchContext.get(el) ?? { found: false }; switchContext.set(el, { value: binding.value, found: prev.found }); } }; const vCase = { beforeMount(el, binding) { const data = getParentAndSwitchValue(el); if (!data || !data.switchValue) return; if (binding.value === data.switchValue.value) { el.style.display = ""; data.switchValue.found = true; } else { el.style.display = "none"; } }, updated(el, binding) { const data = getParentAndSwitchValue(el); if (!data || !data.switchValue) return; if (binding.value === data.switchValue.value) { el.style.display = ""; data.switchValue.found = true; } else { el.style.display = "none"; } } }; const vDefault = { beforeMount(el) { const data = getParentAndSwitchValue(el); if (!data || !data.switchValue) return; el.style.display = data.switchValue.found ? "none" : ""; }, updated(el) { const data = getParentAndSwitchValue(el); if (!data || !data.switchValue) return; el.style.display = data.switchValue.found ? "none" : ""; } }; async function copyListener(value) { await navigator.clipboard.writeText(value); } const vCopy = { mounted(el) { el.addEventListener("click", () => copyListener(el.innerText)); }, unmounted(el) { el.removeEventListener("click", () => copyListener(el.innerText)); } }; function installDirectives(app) { app.directive("focus", vFocus); app.directive("copy", vCopy); app.directive("switch", vSwitch); app.directive("case", vCase); app.directive("default", vDefault); } const marlonWissVueDirectivesPlugin = { install: (app) => { installDirectives(app); } }; export { installDirectives, marlonWissVueDirectivesPlugin, vBlur, vCase, vCopy, vDefault, vFocus, vSwitch };