Bird
Raised Fist0
Vueframework~20 mins

Programmatic navigation with useRouter in Vue - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Programmatic Navigation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when this Vue component calls router.push?

Consider this Vue 3 component using useRouter to navigate:

import { useRouter } from 'vue-router';
import { defineComponent } from 'vue';

export default defineComponent({
  setup() {
    const router = useRouter();
    function goHome() {
      router.push('/home');
    }
    return { goHome };
  }
});

What is the result when goHome() is called?

Vue
import { useRouter } from 'vue-router';
import { defineComponent } from 'vue';

export default defineComponent({
  setup() {
    const router = useRouter();
    function goHome() {
      router.push('/home');
    }
    return { goHome };
  }
});
AThe browser URL changes to '/home' and the app navigates to the Home route without reloading the page.
BAn error is thrown because useRouter cannot be used inside setup.
CNothing happens because router.push requires a callback to work.
DThe browser reloads the entire page and then navigates to '/home'.
Attempts:
2 left
💡 Hint

Think about how Vue Router handles navigation programmatically.

📝 Syntax
intermediate
2:00remaining
Which option correctly uses useRouter to navigate to a named route with params?

Given a route named 'user' that expects a param id, which code correctly navigates to user with id 42?

Arouter.push({ name: 'user', query: { id: 42 } })
Brouter.push('/user/42')
Crouter.push({ name: 'user', params: { id: 42 } })
Drouter.push({ path: 'user', params: { id: 42 } })
Attempts:
2 left
💡 Hint

Named routes use name and params keys.

🔧 Debug
advanced
2:00remaining
Why does this programmatic navigation fail to update the URL?

Look at this code snippet inside a Vue component:

const router = useRouter();
function goProfile() {
  router.push('/profile');
}

// Called on button click

But clicking the button does not change the URL or route. Why?

Vue
const router = useRouter();
function goProfile() {
  router.push('/profile');
}

// Called on button click
<button @click="goProfile">Go</button>
AThe route '/profile' is not defined in the router configuration.
Brouter.push requires await to work properly.
CuseRouter cannot be used inside setup(), it must be imported globally.
DThe <code>goProfile</code> function is not exposed in the component's template context.
Attempts:
2 left
💡 Hint

Check if the function is accessible in the template.

❓ state_output
advanced
2:00remaining
What is the value of currentRoute.path after this navigation?

Given this code inside a Vue 3 component:

import { useRouter, useRoute } from 'vue-router';

const router = useRouter();
const currentRoute = useRoute();

await router.push('/dashboard');

console.log(currentRoute.path);

What will be logged?

Vue
import { useRouter, useRoute } from 'vue-router';

const router = useRouter();
const currentRoute = useRoute();

await router.push('/dashboard');

console.log(currentRoute.path);
A'/dashboard'
BThe old path before navigation
Cundefined
DAn error because currentRoute is not reactive
Attempts:
2 left
💡 Hint

Think about reactivity and when currentRoute updates.

🧠 Conceptual
expert
2:00remaining
Which statement about useRouter and programmatic navigation is true?

Choose the correct statement about useRouter and programmatic navigation in Vue 3.

ACalling <code>router.push()</code> always reloads the entire page.
B<code>useRouter</code> can only be used inside <code>setup()</code> or lifecycle hooks of components.
C<code>useRouter</code> returns a new router instance every time it is called.
DProgrammatic navigation with <code>router.push()</code> does not update the browser URL.
Attempts:
2 left
💡 Hint

Think about where useRouter is designed to be used.

Practice

(1/5)
1. What does the useRouter function provide in a Vue 3 component?
easy
A. A method to style components dynamically
B. A way to fetch data from an API
C. Access to the router instance to navigate programmatically
D. A tool to manage component state

Solution

  1. Step 1: Understand the purpose of useRouter

    useRouter is a Vue Router composable that gives access to the router instance inside setup functions.
  2. Step 2: Identify what the router instance allows

    The router instance allows programmatic navigation, such as using router.push() to change routes.
  3. Final Answer:

    Access to the router instance to navigate programmatically -> Option C
  4. Quick Check:

    useRouter = router access [OK]
Hint: Remember: useRouter gives router control inside components [OK]
Common Mistakes:
  • Thinking useRouter fetches data
  • Confusing useRouter with state management
  • Assuming useRouter styles components
2. Which of the following is the correct syntax to navigate to the '/home' route using useRouter in Vue 3?
easy
A. const router = useRouter(); router.change('/home');
B. const router = useRouter(); router.push('/home');
C. const router = useRouter(); router.navigate('/home');
D. const router = useRouter(); router.go('/home');

Solution

  1. Step 1: Recall the method to change routes programmatically

    The correct method to navigate is router.push().
  2. Step 2: Match the syntax with the correct method

    Only router.push('/home') is valid; other methods like go, navigate, or change do not exist on the router instance.
  3. Final Answer:

    const router = useRouter(); router.push('/home'); -> Option B
  4. Quick Check:

    router.push() navigates routes [OK]
Hint: Use router.push() to navigate routes programmatically [OK]
Common Mistakes:
  • Using router.go() instead of router.push()
  • Trying router.navigate() which is invalid
  • Calling router.change() which doesn't exist
3. Consider this Vue 3 setup code snippet:
import { useRouter } from 'vue-router';
export default {
  setup() {
    const router = useRouter();
    function goToProfile() {
      router.push({ name: 'profile', params: { userId: 42 } });
    }
    return { goToProfile };
  }
}

What happens when goToProfile() is called?
medium
A. The app reloads the current page
B. Nothing happens because router.push requires a string path
C. An error occurs because params cannot be passed this way
D. The app navigates to the route named 'profile' with userId 42 as a parameter

Solution

  1. Step 1: Understand router.push with named routes and params

    Using router.push({ name: 'profile', params: { userId: 42 } }) navigates to the route named 'profile' and passes the parameter userId=42.
  2. Step 2: Confirm this is valid syntax and behavior

    This is the correct way to navigate to a named route with parameters in Vue Router.
  3. Final Answer:

    The app navigates to the route named 'profile' with userId 42 as a parameter -> Option D
  4. Quick Check:

    router.push({name, params}) navigates with params [OK]
Hint: Use object with name and params in router.push() for named routes [OK]
Common Mistakes:
  • Thinking params can't be passed as object
  • Assuming router.push only accepts string paths
  • Confusing params with query parameters
4. Identify the error in this Vue 3 setup function using useRouter:
import { useRouter } from 'vue-router';
export default {
  setup() {
    const router = useRouter;
    function goHome() {
      router.push('/home');
    }
    return { goHome };
  }
}
medium
A. useRouter is not called as a function, missing parentheses
B. router.push should use an object, not a string
C. goHome function is not returned from setup
D. router.push is not a valid method

Solution

  1. Step 1: Check how useRouter is assigned

    The code assigns const router = useRouter; without parentheses, so router is a reference to the function, not the router instance.
  2. Step 2: Understand the impact on router.push call

    Since router is not the router instance, calling router.push() will cause an error because router is not an object with push method.
  3. Final Answer:

    useRouter is not called as a function, missing parentheses -> Option A
  4. Quick Check:

    Call useRouter() with () to get router instance [OK]
Hint: Always call useRouter() with parentheses to get router [OK]
Common Mistakes:
  • Forgetting parentheses after useRouter
  • Using string instead of object incorrectly (not error here)
  • Not returning functions from setup (actually returned here)
5. You want to redirect users to the login page if they are not authenticated after clicking a button. Which Vue 3 setup code correctly uses useRouter for this programmatic navigation?
hard
A. const router = useRouter(); function checkAuth() { if (!isAuthenticated) router.push('/login'); }
B. const router = useRouter; function checkAuth() { if (!isAuthenticated) router.push('/login'); }
C. const router = useRouter(); function checkAuth() { if (!isAuthenticated) router.go('/login'); }
D. const router = useRouter(); function checkAuth() { if (!isAuthenticated) router.navigate('/login'); }

Solution

  1. Step 1: Confirm correct useRouter call

    const router = useRouter(); function checkAuth() { if (!isAuthenticated) router.push('/login'); } correctly calls useRouter() with parentheses to get the router instance.
  2. Step 2: Verify correct navigation method

    const router = useRouter(); function checkAuth() { if (!isAuthenticated) router.push('/login'); } uses router.push('/login'), which is the correct method to navigate programmatically.
  3. Final Answer:

    const router = useRouter(); function checkAuth() { if (!isAuthenticated) router.push('/login'); } -> Option A
  4. Quick Check:

    Call useRouter() and use router.push() for navigation [OK]
Hint: Call useRouter() and use router.push() to redirect [OK]
Common Mistakes:
  • Not calling useRouter as a function
  • Using router.go() or router.navigate() which don't exist
  • Forgetting to check authentication before navigation
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard