Vue interview

Templates and rendering

v-if versus v-show, why v-for needs a stable key, v-if and v-for on the same element, and template refs with defineExpose.

From the template, rendering and template-ref parts of your Rendering, Watchers and Vue app, Directives notes.

Know

  • v-if versus v-show: v-if mounts and unmounts (state lost, hooks run), works with v-else and <template>; v-show toggles display. v-show for frequent toggles.
  • Keys: a stable unique key lets Vue move existing elements and components instead of patching by position; the index behaves like no key. Changing a component's key recreates it.
  • v-if with v-for: in Vue 3 v-if wins, so it can't see the loop variable; filter in a computed or use a wrapping <template>.
  • Arrays: Vue tracks the mutating methods push, pop, shift, unshift, splice, sort, reverse; filter, map, concat and slice return new arrays you assign.
  • Template refs: useTemplateRef() (3.5), filled after mount, null after unmount; for focus, measuring, scrolling and libraries. Child components expose methods with defineExpose.

Fact check of your notes

Gotcha· v-show hides, v-else doesn't

"v-if removes from DOM, v-else only hides (display:none)": it's v-show that only hides. v-else is just the other branch of a v-if.

Gotcha· map is not a mutation method

The note lists map() among the methods Vue reacts to. The tracked mutation methods are push, pop, shift, unshift, splice, sort and reverse; map returns a new array, like filter.

Gotcha· Binding an object of attributes has no argument

<Comp v-bind:obj> binds a single attribute named obj. To spread an object's properties as attributes or props, write v-bind="obj".

Exercise

Exercise
  • Render a list of inputs keyed by index, type into the second one, remove the first item and watch the text move; switch to an id key and repeat.
  • Build a modal component that exposes open() and close() with defineExpose, and open it from a parent through a template ref.

Be able to say

Be able to say· Why do list items need a key?

"Without a key Vue patches by position, so state that lives in the elements, like input text, focus or a child component's state, stays where it was while the data moves. A stable id lets Vue match elements to items and move them. The index is no better than no key, because removing one item shifts every index after it."

Your notes

Open in Notes

Nothing yet. Notes filed here show up on this page and the section overview.