Vue JS Vue JS Router and Navigation 1 — Questions and Answers
Question 1: Which Vue Router function is used to programmatically navigate to a new route?
- router.push() (Correct answer)
- router.go()
- router.navigate()
- router.redirect()
Correct answer: router.push()
router.push() adds a new entry to the browser history stack and navigates to the specified route.
Question 2: What is the difference between router.push() and router.replace() in Vue Router?
- push() is async; replace() is sync
- push() adds to history; replace() replaces the current history entry (Correct answer)
- push() supports named routes; replace() does not
- replace() requires a full page reload
Correct answer: push() adds to history; replace() replaces the current history entry
router.replace() navigates to a route without pushing a new entry onto the history stack, so the back button does not return to the previous route.
Question 3: How do you define a dynamic route segment in Vue Router?
- Using curly braces: {id}
- Using a colon prefix: :id (Correct answer)
- Using brackets: [id]
- Using angle brackets: <id>
Correct answer: Using a colon prefix: :id
Dynamic segments are defined with a colon prefix (e.g., /user/:id), and the value is accessible via route.params.id.
Question 4: Which Vue Router component renders the matched component for the current route?
- <router-view> (Correct answer)
- <router-link>
- <route-outlet>
- <nav-view>
Correct answer: <router-view>
<router-view> is the outlet component that displays the component matched by the current route path.
Question 5: What navigation guard runs before every route change at the router level?
- router.afterEach()
- router.beforeResolve()
- router.beforeEach() (Correct answer)
- router.onError()
Correct answer: router.beforeEach()
router.beforeEach() registers a global guard that runs before every navigation and can block or redirect the navigation.
Question 6: How do you pass query parameters when navigating programmatically with Vue Router?
- router.push({ path: '/search', params: { q: 'vue' } })
- router.push({ path: '/search', query: { q: 'vue' } }) (Correct answer)
- router.push('/search?q=vue') only
- router.push({ name: 'search', search: { q: 'vue' } })
Correct answer: router.push({ path: '/search', query: { q: 'vue' } })
Query parameters are passed via the query object in the route location descriptor and appear as ?key=value in the URL.
Which Vue Router function is used to programmatically navigate to a new route?