Bird
Raised Fist0
Vueframework~20 mins

Creating custom directives in Vue - Practice Exercises

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Vue Directive Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this Vue custom directive usage?
Consider this Vue 3 custom directive that changes the background color of an element when it is mounted. What will be the background color of the
after the component renders?
Vue
import { createApp } from 'vue';

const app = createApp({});

app.directive('highlight', {
  mounted(el, binding) {
    el.style.backgroundColor = binding.value || 'yellow';
  }
});

app.component('TestComponent', {
  template: `<div v-highlight="'lightblue'">Hello</div>`
});

app.mount('#app');
AThe div background color will be red
BThe div background color will be lightblue
CThe div background color will be transparent
DThe div background color will be yellow
Attempts:
2 left
💡 Hint
Look at the binding.value used in the directive and the value passed in the template.
📝 Syntax
intermediate
2:00remaining
Which option correctly defines a Vue 3 custom directive that focuses an input element when mounted?
Select the correct syntax for a Vue 3 custom directive named 'focus' that automatically focuses the element when it is inserted into the DOM.
A
app.directive('focus', {
  mounted(el) {
    el.focus();
  }
});
B
app.directive('focus', {
  inserted(el) {
    el.focus();
  }
});
C
app.directive('focus', {
  bind(el) {
    el.focus();
  }
});
D
app.directive('focus', {
  created(el) {
    el.focus();
  }
});
Attempts:
2 left
💡 Hint
Check the Vue 3 directive lifecycle hooks. 'mounted' is the correct hook for when the element is inserted.
🔧 Debug
advanced
2:00remaining
Why does this custom directive fail to update the element's text when the bound value changes?
Given this Vue 3 custom directive, the text content of the element does not update when the bound value changes. What is the cause?
Vue
app.directive('text', {
  mounted(el, binding) {
    el.textContent = binding.value;
  }
});

// Usage in template: <p v-text="message"></p>
AThe directive is missing a beforeMount hook to initialize the text.
BThe binding.value is undefined, so textContent is not set.
CThe directive should use el.innerText instead of el.textContent.
DThe directive only updates text in the mounted hook, it should also update in the updated hook.
Attempts:
2 left
💡 Hint
Think about what happens when the bound value changes after the element is mounted.
🧠 Conceptual
advanced
2:00remaining
What is the purpose of the 'beforeUnmount' hook in a Vue 3 custom directive?
In Vue 3 custom directives, what does the 'beforeUnmount' hook allow you to do?
AIt initializes the directive's state before the element is mounted.
BIt updates the element's content before the component re-renders.
CIt allows cleanup of event listeners or resources before the element is removed from the DOM.
DIt delays the mounting of the element until a condition is met.
Attempts:
2 left
💡 Hint
Think about what happens just before the element disappears from the page.
❓ state_output
expert
3:00remaining
What will be the final text content of the

element after the component updates?

Given this Vue 3 custom directive and component code, what will the

element display after the message changes from 'Hello' to 'World'?

Vue
const app = Vue.createApp({
  data() {
    return { message: 'Hello' };
  },
  template: `<p v-text-update="message"></p>`
});

app.directive('text-update', {
  mounted(el, binding) {
    el.textContent = binding.value;
  },
  updated(el, binding) {
    el.textContent = binding.oldValue + ' ' + binding.value;
  }
});

app.mount('#app');

// Later in code: app.message = 'World';
AHello World
BWorld
CHello
Dundefined World
Attempts:
2 left
💡 Hint
Look at how the updated hook uses binding.oldValue and binding.value to set textContent.

Practice

(1/5)
1. What is the main purpose of creating a custom directive in Vue?
easy
A. To add reusable behavior to HTML elements
B. To define new components
C. To manage Vuex state
D. To handle routing between pages

Solution

  1. Step 1: Understand what directives do in Vue

    Directives are special markers on elements that tell Vue to do something with that element.
  2. Step 2: Identify the role of custom directives

    Custom directives let you add reusable behavior to elements, like focusing an input or changing styles dynamically.
  3. Final Answer:

    To add reusable behavior to HTML elements -> Option A
  4. Quick Check:

    Custom directives = reusable element behavior [OK]
Hint: Custom directives add behavior to elements, not components [OK]
Common Mistakes:
  • Confusing directives with components
  • Thinking directives manage app state
  • Assuming directives handle routing
2. Which of the following is the correct syntax to register a global custom directive named v-focus in Vue 3?
easy
A. Vue.directive('v-focus', function(el) { el.focus() })
B. app.directive('focus', { mounted(el) { el.focus() } })
C. app.directive('v-focus', { bind(el) { el.focus() } })
D. Vue.createDirective('focus', { mounted(el) { el.focus() } })

Solution

  1. Step 1: Recall Vue 3 global directive registration

    In Vue 3, you use the app instance's directive method with the directive name without the 'v-' prefix.
  2. Step 2: Check the lifecycle hook and syntax

    The correct hook for when the element is inserted is 'mounted', and the function receives the element as argument.
  3. Final Answer:

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

    Vue 3 global directive = app.directive('name', { mounted }) [OK]
Hint: Use app.directive('name', { mounted }) without 'v-' prefix [OK]
Common Mistakes:
  • Including 'v-' prefix in directive name
  • Using Vue.directive instead of app.directive in Vue 3
  • Using deprecated hooks like 'bind'
3. Given this custom directive registered globally in Vue 3:
app.directive('color', {
  mounted(el, binding) {
    el.style.color = binding.value
  },
  updated(el, binding) {
    el.style.color = binding.value
  }
})
What will be the text color of the paragraph after the component updates if used as <p v-color="'red'">Hello</p> and later the binding value changes to 'blue'?
medium
A. The text color will be black (default)
B. The text color will remain red
C. The text color will change to blue
D. There will be a runtime error

Solution

  1. Step 1: Understand directive lifecycle hooks

    The 'mounted' hook sets the color initially, and the 'updated' hook runs when the binding value changes.
  2. Step 2: Trace the color change on update

    When the binding value changes to 'blue', the 'updated' hook sets the element's color style to 'blue'.
  3. Final Answer:

    The text color will change to blue -> Option C
  4. Quick Check:

    updated hook changes color to new binding value [OK]
Hint: updated hook runs on binding change to update element [OK]
Common Mistakes:
  • Assuming color stays as initial value
  • Ignoring the updated lifecycle hook
  • Thinking directive causes errors on update
4. Consider this custom directive code snippet in Vue 3:
app.directive('tooltip', {
  mounted(el, binding) {
    el.setAttribute('title', binding.value)
  },
  updated(el, binding) {
    el.setAttribute('title', binding.oldValue)
  }
})
What is the problem with this directive when the binding value changes?
medium
A. The tooltip title does not update to the new value
B. The directive causes a syntax error
C. The title attribute is removed on update
D. The directive works correctly with no issues

Solution

  1. Step 1: Analyze the updated hook usage

    The updated hook sets the title attribute to binding.oldValue, which is the previous value, not the new one.
  2. Step 2: Understand the effect on the tooltip

    Because it sets the old value on update, the tooltip does not reflect the new binding value after change.
  3. Final Answer:

    The tooltip title does not update to the new value -> Option A
  4. Quick Check:

    updated hook must use binding.value, not binding.oldValue [OK]
Hint: Use binding.value in updated hook, not binding.oldValue [OK]
Common Mistakes:
  • Using binding.oldValue instead of binding.value on update
  • Assuming no update needed for title
  • Confusing syntax error with logic error
5. You want to create a custom directive v-auto-focus that automatically focuses an input element only when it is inserted into the DOM and not on updates. Which is the best way to implement this directive in Vue 3?
hard
A. Use the created hook to call el.focus()
B. Use the updated hook to call el.focus() every time the binding changes
C. Use both mounted and updated hooks to call el.focus()
D. Use the mounted hook to call el.focus() and leave updated empty

Solution

  1. Step 1: Identify when to focus the element

    The input should be focused only once when inserted, so the 'mounted' hook is the right place.
  2. Step 2: Avoid focusing on updates

    Calling focus in 'updated' would focus repeatedly, which is not desired.
  3. Step 3: Understand Vue 3 lifecycle hooks

    There is no 'created' hook for directives; 'mounted' is the earliest for DOM access.
  4. Final Answer:

    Use the mounted hook to call el.focus() and leave updated empty -> Option D
  5. Quick Check:

    Focus on mounted only, not updated [OK]
Hint: Focus in mounted hook only to avoid repeated focusing [OK]
Common Mistakes:
  • Focusing in updated hook causing repeated focus
  • Using non-existent created hook for directives
  • Calling focus multiple times unnecessarily
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