Implement Vue custom directives: hook order in the renderer, binding values, v-click-outside and v-intersect
Problem
A custom directive is an object of lifecycle hooks that Vue calls with the real element. They are the right tool for low-level DOM behaviour that does not need its own component: closing a menu on an outside click, lazy-loading an image when it scrolls into view, autofocus. Interviewers ask about them to see whether you know when each hook runs and what the element looks like at that moment. Build the runtime part and two directives on a small renderer.
const menu = withDirectives(h("ul", null, items), [[vClickOutside, close]]);
render(menu, container);
dispatch(document.body, "click"); // close(event)
const img = withDirectives(h("img"), [[vIntersect, { handler: load, options: { rootMargin: "200px" } }, undefined, { once: true }]]);Ref. UR-1464 · © UIRound · uiround.com/questions/implement-vue-custom-directives-hook-order-in-the-renderer-binding-values-v-click-outside-and-v-intersect
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
- 5
- code listings
- 7
- edge cases
- 5
- follow-up questions
What's inside
- The full problem, with examples
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Stuck? Take a hint
- 1
withDirectivesjust puts bindings{ dir, value, oldValue, arg, modifiers }on the vnode; a function directive becomes{ mounted: fn, updated: fn }.invokeDirectiveHookcopiesoldValuefrom the previous binding at the same index and callsdir[name](el, binding, vnode, prevVNode).
Try it in the editor
Run your code as often as you like. Submitting it to the full test suite is part of Pro.
Private, and saved in this browser as you type. All your notes are on My lists.