💚 Vue.js Beginner

What are Vue directives?

Why Interviewers Ask This

This question tests conceptual clarity. Interviewers want to hear a precise, confident definition before moving to more complex Vue.js topics. It also reveals how well you can explain technical ideas to non-experts.

Answer

Directives are special HTML attributes with the v- prefix that apply reactive behavior to DOM elements. Built-in directives: v-if / v-else-if / v-else: conditionally render elements (removes/creates from DOM): <div v-if="isLoggedIn">Welcome</div><div v-else>Login</div>; v-show: toggle visibility with CSS display (keeps in DOM): <div v-show="isVisible">. Use v-if for infrequently toggled elements, v-show for frequently toggled; v-for: render a list: <li v-for="(item, index) in items" :key="item.id">{{ item.name }}</li>. Always use :key; v-bind (shorthand :): bind an attribute or prop: <img :src="imageUrl" :class="{ active: isActive }">; v-on (shorthand @): listen to events: <button @click="handleClick">; v-model: two-way data binding: <input v-model="searchText">; v-text: set element text content; v-html: set innerHTML (XSS risk — use only with trusted content); v-once: render only once, skip future updates; v-memo: memoize a subtree, re-render only when dependencies change; v-cloak: hide uncompiled template until ready; v-pre: skip compilation for this element. Custom directives: register with app.directive("highlight", { mounted(el) { el.style.background = "yellow"; } }).

Common Mistake

Rushing to answer is a common mistake. Take two seconds to structure your response: definition → example → trade-off. This structure makes complex Vue.js answers easy to follow.