Challenge your understanding of Vue's core directives—v-if, v-for, and v-model—with scenario-based questions that test practical usage, syntax, and common pitfalls in template logic. Sharpen your Vue skills with targeted questions designed for optimal comprehension and retention.
Which code snippet properly toggles a paragraph’s visibility based on a Boolean variable called 'isVisible' using v-if?
Explanation: The v-if directive is correctly used with the syntax v-if='isVisible', which conditionally renders the element when isVisible is true. The options v.show and v.visible are not valid Vue directives and won't work. The option :v-if uses a binding syntax that is unnecessary and incorrect for v-if. Only the first option reflects proper Vue syntax.
If you have an array 'fruits' and want to display each fruit in a list, which v-for syntax is correct in Vue templates?
Explanation: The correct syntax for v-for in Vue is v-for='(item, index) in array', accompanied by a unique :key for better performance, such as :key='index'. The other options use incorrect syntax: 'from', 'index:', and 'of' are not valid, and missing the v-for directive or using 'key' instead of ':key' is invalid.
Given an input field bound to a data property 'username', which statement best demonstrates two-way data binding in Vue using v-model?
Explanation: v-model is the dedicated directive for enabling two-way data binding with form inputs in Vue. v-bind only creates one-way binding, and v-bind:model is not a valid directive. The plain 'model' attribute is invalid in Vue. Only v-model achieves real two-way synchronization between the input and the data property.
When rendering an element with v-if and another element with v-else, what must be true for Vue to handle the condition correctly?
Explanation: Vue requires that v-if and v-else elements are adjacent siblings so it knows which elements to toggle depending on the condition. Nesting v-else inside v-if, or using v-if on both, does not enable the intended alternate rendering. The statement that v-else can only be used with v-for is incorrect; v-else works with v-if conditions.
Why should you avoid using array indexes as keys in v-for, and what is a better alternative?
Explanation: Using array indexes as keys may cause rendering inefficiencies and bugs during reordering or updates, because Vue can have trouble tracking elements correctly. Class attributes do not replace keys, and using names does not break the app—it's often preferred if unique. Indexes do not prevent data updates or convert lists to objects; these statements are inaccurate.