Question presented to candidate:
"Vue templates are full of attributes that start with v-. What is a directive, which ones do you use every day, and can you write your own?"
What a strong answer should cover:
- A directive is a special
v-attribute that applies reactive behaviour to the DOM when its value changes; anatomyv-name:arg.modifiers="expression". - The everyday built-ins:
v-if/v-else-if/v-else,v-show,v-for(with:key),v-bind(:),v-on(@),v-model, plusv-slot(#),v-text,v-html,v-pre,v-once,v-memoandv-cloak. - Most built-ins are compiled away into plain JavaScript (
v-ifbecomes a ternary,v-forarenderListcall,v-onanonClickprop);v-model,v-showand custom directives stay as runtime directives applied withwithDirectives. - Custom directives are objects with lifecycle hooks (
created,mounted,updated,beforeUnmount,unmountedand so on) that receive the element and abinding(value,arg,modifiers); in<script setup>anyvXxxvariable becomesv-xxx. - Use a custom directive for low-level DOM access (focus, tooltips, intersection observers); prefer components or composables for anything else.
Clarifying questions expected:
- "Should I focus on the built-ins, or on writing a custom one?"
Code / implementation expected: Optional. A template using the common directives; a custom directive is a plus.