Router Access

Back

Loading concept...

Vue Router Access: Your Navigation Control Room 🎮

Imagine you’re a pilot in an airplane cockpit. You have instruments that tell you where you are (Route Object), controls that let you fly to new places (Programmatic Navigation), and the whole control system that makes everything work (Router Instance). Vue Router Access is exactly like this!


The Big Picture: Why Does This Matter?

In a Vue app, pages don’t reload like old websites. Instead, Vue Router is the magic controller that:

  • Knows which page you’re on
  • Takes you to new pages without refreshing
  • Remembers where you’ve been

Router Access means getting your hands on these controls so YOU can drive!


1. Router Instance: The Master Control

Think of the Router Instance as the main brain of your navigation system. It’s the whole machine that handles all the route changes.

What is it?

The router instance is the object you create when setting up Vue Router. It contains:

  • All your routes (the list of pages)
  • Methods to navigate
  • The current state of navigation

Simple Example

// Creating the router instance
import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', component: Home },
    { path: '/about', component: About }
  ]
})

// Using it in your app
app.use(router)

Real Life Analogy:

  • The router instance = The GPS device in your car
  • Routes = All the addresses it knows
  • You plug it in (use it) and now your car can navigate!

2. Route Object: Where Are You Right Now?

The Route Object is like looking at your GPS screen and seeing:

  • Your current address
  • How you got here
  • Any special notes about this location

What’s Inside the Route Object?

graph LR A["Route Object"] --> B["path: '/user/42'"] A --> C["params: id = 42"] A --> D["query: tab = 'profile'"] A --> E["name: 'UserPage'"] A --> F["fullPath: '/user/42?tab=profile'"]

The Properties You’ll Use Most

Property What It Tells You Example
path The URL path /products/shoes
params Dynamic pieces { id: '42' }
query The ?stuff=here part { search: 'blue' }
name Route’s nickname 'ProductDetail'
fullPath Everything combined /products/42?color=red

Example in Action

// If URL is: /user/123?tab=settings

route.path     // '/user/123'
route.params   // { id: '123' }
route.query    // { tab: 'settings' }
route.fullPath // '/user/123?tab=settings'

Think of it like a letter:

  • path = The street address
  • params = The apartment number
  • query = Special delivery instructions

3. Programmatic Navigation: Drive Without Clicking!

Clicking links is cool, but sometimes you want to navigate automatically - like after a form submission or when something happens.

The Three Ways to Navigate

graph TD A["Programmatic Navigation"] --> B["router.push - Go forward"] A --> C["router.replace - Swap current"] A --> D["router.go - Jump in history"]

3.1 router.push() - The Main Way

// Go to a new page (adds to history)
router.push('/about')

// Using a route name
router.push({ name: 'UserProfile' })

// With parameters
router.push({
  name: 'User',
  params: { id: 42 }
})

// With query string
router.push({
  path: '/search',
  query: { keyword: 'vue' }
})

Like pressing “Navigate” on your GPS! The old location stays in history.

3.2 router.replace() - Swap Without History

// Replace current page (no back button)
router.replace('/new-page')

Use this when:

  • User logs in → replace login page with dashboard
  • Correcting a typo in URL
  • You don’t want them going “back” to the current page

3.3 router.go() - Time Travel!

router.go(1)   // Go forward 1 step
router.go(-1)  // Go back 1 step (like Back button)
router.go(-3)  // Go back 3 steps

Like the Back/Forward buttons in your browser!


4. useRouter Composable: Get the Controls!

In Vue 3’s Composition API, useRouter() is how you grab the router inside your components.

The Setup

import { useRouter } from 'vue-router'

export default {
  setup() {
    const router = useRouter()

    function goToProfile() {
      router.push('/profile')
    }

    function goBack() {
      router.go(-1)
    }

    return { goToProfile, goBack }
  }
}

Script Setup (Even Simpler!)

<script setup>
import { useRouter } from 'vue-router'

const router = useRouter()

function handleLogin() {
  // After successful login...
  router.push('/dashboard')
}
</script>

Why useRouter()?

  • Works in Composition API
  • Clean and organized
  • Can be used in any setup function

5. useRoute Composable: Know Where You Are!

While useRouter gives you the controls, useRoute gives you information about your current location.

Getting Current Route Info

import { useRoute } from 'vue-router'

export default {
  setup() {
    const route = useRoute()

    // Now you can access:
    console.log(route.path)    // '/user/42'
    console.log(route.params)  // { id: '42' }
    console.log(route.query)   // { tab: 'settings' }

    return { route }
  }
}

Reactive and Always Current!

<script setup>
import { useRoute } from 'vue-router'
import { watch } from 'vue'

const route = useRoute()

// Watch for route changes!
watch(
  () => route.params.id,
  (newId) => {
    console.log('User ID changed to:', newId)
    // Fetch new user data...
  }
)
</script>

<template>
  <div>
    <h1>Viewing User: {{ route.params.id }}</h1>
    <p>Current tab: {{ route.query.tab }}</p>
  </div>
</template>

Quick Comparison: useRouter vs useRoute

graph LR A["useRouter"] --> B["Controls Navigation"] A --> C["push, replace, go"] A --> D["Action: GO somewhere"] E["useRoute"] --> F["Reads Location"] E --> G["path, params, query"] E --> H["Info: WHERE am I?"]
useRouter useRoute
Purpose Navigate Read info
Returns Router instance Current route
Actions push, replace, go -
Info - path, params, query
Analogy Steering wheel GPS display

Real-World Example: Putting It All Together!

<script setup>
import { useRouter, useRoute } from 'vue-router'
import { ref, watch } from 'vue'

const router = useRouter()
const route = useRoute()

const searchTerm = ref('')

// Read current search from URL
searchTerm.value = route.query.search || ''

// Navigate to search results
function doSearch() {
  router.push({
    path: '/search',
    query: { search: searchTerm.value }
  })
}

// Go back to home
function goHome() {
  router.push('/')
}

// Watch for URL changes
watch(() => route.query.search, (newSearch) => {
  if (newSearch) {
    searchTerm.value = newSearch
  }
})
</script>

<template>
  <div>
    <input v-model="searchTerm" />
    <button @click="doSearch">Search</button>
    <button @click="goHome">Home</button>

    <p>Current path: {{ route.path }}</p>
  </div>
</template>

The Golden Rules 🌟

  1. Need to GO somewhere? → Use useRouter() + push/replace
  2. Need to KNOW where you are? → Use useRoute()
  3. After form submit? → Use router.push() to redirect
  4. Hide login page after login? → Use router.replace()
  5. Read URL parameters? → Use route.params or route.query

You Did It! 🎉

You now understand Vue Router Access like a pro:

  • Router Instance = The whole navigation system
  • Route Object = Your current location info
  • Programmatic Navigation = Driving without clicking links
  • useRouter = Grab the steering wheel
  • useRoute = Check your GPS display

Now go build something amazing! Your Vue apps can navigate anywhere! 🚀

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.