Bird
Raised Fist0
Vueframework~20 mins

Why custom directives matter in Vue - Challenge Your Understanding

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Custom Directive Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when a custom directive updates an element?
Consider a Vue 3 component using a custom directive that changes the background color of an element when the directive's value changes. What will be the background color after the value updates from 'red' to 'blue'?
Vue
const app = Vue.createApp({
  data() {
    return { color: 'red' };
  },
  template: `<div v-color-bg="color">Hello</div>`
});

app.directive('color-bg', {
  beforeMount(el, binding) {
    el.style.backgroundColor = binding.value;
  },
  updated(el, binding) {
    el.style.backgroundColor = binding.value;
  }
});

const vm = app.mount('#app');

// Then later in code: vm.color = 'blue';
AThe background color will be blue after the update.
BThe background color will remain red because updated hook is not called.
CThe background color will be removed because the directive does not handle unmount.
DThe background color will be green by default.
Attempts:
2 left
💡 Hint
Think about which directive lifecycle hook runs when the bound value changes.
🧠 Conceptual
intermediate
1:30remaining
Why use custom directives instead of methods for DOM manipulation?
Which reason best explains why custom directives are preferred for direct DOM manipulation in Vue over using methods inside components?
ACustom directives run only once, methods run multiple times causing performance issues.
BMethods cannot access the DOM at all in Vue components.
CCustom directives encapsulate DOM logic and keep templates clean, while methods are for data logic.
DMethods automatically update the DOM without needing directives.
Attempts:
2 left
💡 Hint
Think about separation of concerns between DOM and data logic.
📝 Syntax
advanced
2:00remaining
Identify the correct syntax for a Vue 3 custom directive definition
Which option shows the correct way to define a Vue 3 custom directive that logs a message when the element is mounted?
A
app.directive('log', {
  mounted(el) {
    console.log('Element mounted');
  }
});
B
app.directive('log', (el) =&gt; {
  console.log('Element mounted');
});
C
app.directive('log', {
  bind(el) {
    console.log('Element mounted');
  }
});
D
app.directive('log', {
  created(el) {
    console.log('Element mounted');
  }
});
Attempts:
2 left
💡 Hint
Check Vue 3 directive lifecycle hook names.
🔧 Debug
advanced
2:00remaining
Why does this custom directive fail to update on value change?
Given this directive code, why does the element's text color not update when the bound value changes? app.directive('text-color', { beforeMount(el, binding) { el.style.color = binding.value; } });
ABecause 'beforeMount' runs after the element is removed from DOM.
BBecause the directive lacks an 'updated' hook to handle value changes.
CBecause 'binding.value' is undefined in 'beforeMount'.
DBecause the directive should use 'mounted' instead of 'beforeMount'.
Attempts:
2 left
💡 Hint
Consider which lifecycle hooks run when the value changes.
❓ state_output
expert
2:30remaining
What is the final text content after directive and reactive state update?
In this Vue 3 example, what will be the final text content of the

element after the button is clicked? const app = Vue.createApp({ data() { return { count: 0 }; }, template: `

Initial

` }); app.directive('text-update', { mounted(el, binding) { el.textContent = `Count is ${binding.value}`; }, updated(el, binding) { el.textContent = `Count is ${binding.value}`; } }); app.mount('#app');
AThe text content will be empty after clicking the button.
B"Initial" remains because directives do not update textContent.
C"Count is 0" even after clicking the button.
D"Count is 1" after clicking the button once.
Attempts:
2 left
💡 Hint
Think about how the directive updates textContent on reactive changes.

Practice

(1/5)
1. Why are custom directives useful in Vue?
easy
A. They add reusable behaviors directly to HTML elements.
B. They replace Vue components entirely.
C. They automatically fetch data from APIs.
D. They style elements with CSS only.

Solution

  1. Step 1: Understand the purpose of custom directives

    Custom directives let you add special behaviors to HTML elements that you can reuse.
  2. Step 2: Compare with other options

    They do not replace components, fetch data, or only style elements; they control DOM behavior.
  3. Final Answer:

    They add reusable behaviors directly to HTML elements. -> Option A
  4. Quick Check:

    Custom directives = reusable element behaviors [OK]
Hint: Custom directives add behaviors to elements, not replace components [OK]
Common Mistakes:
  • Thinking directives replace components
  • Confusing directives with data fetching
  • Assuming directives only style elements
2. Which is the correct syntax to register a global custom directive named focus in Vue 3?
easy
A. app.component('focus', { mounted(el) { el.focus() } })
B. Vue.directive('focus', function(el) { el.focus() })
C. app.directive('focus', { mounted(el) { el.focus() } })
D. app.use('focus', { mounted(el) { el.focus() } })

Solution

  1. Step 1: Recall Vue 3 global directive registration

    In Vue 3, use app.directive(name, definition) to register directives globally.
  2. Step 2: Check the options

    app.directive('focus', { mounted(el) { el.focus() } }) uses app.directive with a proper object containing mounted hook. Others use wrong methods or syntax.
  3. Final Answer:

    app.directive('focus', { mounted(el) { el.focus() } }) -> Option C
  4. Quick Check:

    Vue 3 global directive = app.directive(name, definition) [OK]
Hint: Use app.directive() with hooks to register global directives [OK]
Common Mistakes:
  • Using Vue.directive instead of app.directive in Vue 3
  • Using app.use or app.component incorrectly
  • Passing a function instead of an object with hooks
3. Given this custom directive code:
app.directive('highlight', {
  mounted(el) {
    el.style.backgroundColor = 'yellow'
  }
})

What will happen when you use <div v-highlight>Text</div> in your template?
medium
A. The div will have a yellow border but no background change.
B. The div's text color changes to yellow.
C. Nothing happens because the directive is missing a bind hook.
D. The div's background color will become yellow when inserted into the DOM.

Solution

  1. Step 1: Understand the mounted hook effect

    The mounted hook runs when the element is inserted, setting backgroundColor to yellow.
  2. Step 2: Analyze the directive usage

    Using v-highlight applies the directive, so the div's background becomes yellow, not border or text color.
  3. Final Answer:

    The div's background color will become yellow when inserted into the DOM. -> Option D
  4. Quick Check:

    mounted hook sets backgroundColor = yellow [OK]
Hint: mounted hook runs on insert, sets styles immediately [OK]
Common Mistakes:
  • Confusing background color with border or text color
  • Thinking bind hook is required in Vue 3
  • Assuming directive does nothing without update hook
4. Identify the error in this custom directive code:
app.directive('scroll', {
  mounted(el) {
    window.addEventListener('scroll', () => {
      el.textContent = window.scrollY
    })
  },
  unmounted() {
    window.removeEventListener('scroll')
  }
})
medium
A. The directive should use updated instead of mounted.
B. The removeEventListener call is missing the event handler function.
C. The mounted hook should not use arrow functions.
D. The unmounted hook should be named destroyed.

Solution

  1. Step 1: Check event listener removal

    removeEventListener requires the same event and handler function to remove the listener properly.
  2. Step 2: Analyze the unmounted hook

    Here, removeEventListener is called without the handler function, so the listener stays active causing memory leaks.
  3. Final Answer:

    The removeEventListener call is missing the event handler function. -> Option B
  4. Quick Check:

    removeEventListener needs event and handler [OK]
Hint: Always pass same handler to removeEventListener as added [OK]
Common Mistakes:
  • Omitting handler in removeEventListener
  • Confusing unmounted with destroyed hook
  • Thinking arrow functions cause errors here
5. You want to create a custom directive v-auto-focus that focuses an input only when it is visible on the page (not hidden by CSS). Which approach best uses custom directives to achieve this?
hard
A. In the mounted hook, check if el.offsetParent !== null before calling el.focus().
B. Use the updated hook to call el.focus() unconditionally every time.
C. Add a watcher on a data property to call el.focus() inside the directive.
D. Use a global event listener on window resize to focus the element.

Solution

  1. Step 1: Understand visibility check in directives

    Checking el.offsetParent !== null confirms the element is visible (not hidden by CSS).
  2. Step 2: Apply focus conditionally in mounted hook

    Focusing only when visible avoids errors and unwanted focus on hidden inputs.
  3. Step 3: Evaluate other options

    Updated hook focusing unconditionally may cause focus flicker; watchers and global listeners add complexity.
  4. Final Answer:

    In the mounted hook, check if el.offsetParent !== null before calling el.focus(). -> Option A
  5. Quick Check:

    Check visibility before focus in mounted hook [OK]
Hint: Check element visibility before focus in mounted hook [OK]
Common Mistakes:
  • Focusing without visibility check
  • Using updated hook causing repeated focus
  • Adding unnecessary watchers or global listeners
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard