All jobs / Frontend / web developer / Vue
Frontend / web developer interview question · 1–3 years
A user page loads its data in onMounted. Clicking from /users/1 to /users/2 changes the URL, but the page still shows user 1.
Why, and how do you fix it?
The strongest answer
Vue Router reuses the same component instance when only the param changes, so onMounted does not run again. Watch the route param — or take it as a prop and watch that — and refetch
Why it works
Right — same route record, same instance, no remount. React to the param instead of relying on the mount hook.
What a good answer covers
- Same component, new params: no remount.
- Don’t rely on onMounted for params.
- Watch the param or the prop.
- Cancel the stale request too.
Answers that fall short
- Close, but not the strongest: Put a key on the router view based on the full path so the component is recreated on every navigation
It works, but it remounts every page on every navigation; watching the param is the targeted fix. - Weak: The router is caching pages, so I would turn its cache off
There is no page cache involved; the instance is simply reused because the matched component did not change. - Red flag: Replace the links with plain anchors so the browser reloads the page for each user
Full reloads throw away the SPA and its state to avoid writing one watcher.
Who gets asked this
More Vue questions
- What is wrong with the composable, and what is the contract a composable should follow?
- How do you restructure state, and what rule do you give the team?
- A five-year-old Vue codebase is on Vue 3 but written entirely in the Options API with mixins and Vuex. Some…
- A child component receives a quantity prop and has plus and minus buttons. In Vue, how should the child…
- In a Vue 3 component using script setup, you try to focus an input through a template ref at the top of setup…
- In setup, a developer writes const { count } = state, where state is a reactive object. The template shows…
- In Vue, when do you use a computed property and when a watcher?