0
0
Vueframework~15 mins

Programmatic navigation with useRouter in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Programmatic navigation with useRouter in Vue
📖 Scenario: You are building a simple Vue app with two pages: Home and About. You want to add a button on the Home page that, when clicked, takes the user to the About page using Vue Router's programmatic navigation.
🎯 Goal: Create a Vue component for the Home page that uses useRouter to navigate to the About page when a button is clicked.
📋 What You'll Learn
Create a Vue component named HomeView with a button labeled 'Go to About'.
Import and use useRouter from vue-router inside the component's setup function.
Define a function named goToAbout that uses the router to navigate to the '/about' route.
Attach the goToAbout function to the button's click event.
💡 Why This Matters
🌍 Real World
Programmatic navigation is common in Vue apps when you want to move users between pages after actions like form submission or button clicks without using links.
💼 Career
Understanding how to use useRouter for navigation is essential for Vue developers building interactive single-page applications.
Progress0 / 4 steps
1
Create the HomeView component skeleton
Create a Vue component named HomeView with a template containing a button with the text 'Go to About'.
Vue
Need a hint?

Start by writing the template with a button inside. No script code needed yet.

2
Import useRouter and create router instance
Inside the <script setup> block, import useRouter from vue-router and create a constant named router by calling useRouter().
Vue
Need a hint?

Use ES module import syntax to import useRouter. Then call it to get the router instance.

3
Define the goToAbout function to navigate programmatically
Inside the <script setup> block, define a function named goToAbout that calls router.push('/about') to navigate to the About page.
Vue
Need a hint?

Define a normal function that calls router.push with the path string.

4
Attach goToAbout to the button click event
In the template, add a @click event to the button that calls the goToAbout function when clicked.
Vue
Need a hint?

Use Vue's event binding syntax @click on the button to call the function.