6 months ago

Learn vue: Router

Vue

6 months ago

Learn vue: Router

First setup RouterView

This is where vue router will display your pages. if you're coming from React.js like me, its similiar to Outlet component in React router dom

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

<template>
 <RouterView />
</template>

Register your pages

You need to register your pages so Vue Router can recognize them

import { createRouter, createWebHistory } from 'vue-router'
import Home from './pages/home.vue'

const router = createRouter({
 history: createWebHistory(),
 routes: [
  {
    path: "/",
    name: "home",
    component: Home
  }
 ]
})

So. what the purpose of this part?

  1. createRouter is used to create router instance, it's similiar to when i develop React.js app using react router dom, theres function called createBrowserRouter

  2. createWebHistoryis one of the modes to setup history modes, vue router offers several history modes, but for now im using createWebHistory so that the url looks clean, without hash

  3. routes is where you define all your routes, when you add route there are two main things you need: path which is the url, and component which is vue component. so when someone visit that url vue router will display its. There's also another property called name, it purpose is to give each router unique identifier, this comes when you want to navigate programmatically. For example instead of using hardcoded url, you can do something like router.push({ name: "home" }). it makes your code easer to manage, especially when routes get more complex

    name property works as unique identifier for router, it reminds me of similar concept in Laravel, where you can also give route a name, this way you dont need to hardcode the path everytime you want to navigate. For example

    Route::get('/', [HomeController::class, 'index'])->name('home');

Registering Router in Your Vue App

After setting up your routes, you need to register router in your vue app so it knows how handle navigation

import { createApp } from 'vue'
import App from './App.vue'
import router from './routes'

const app = createApp(App)
app.use(router)
app.mount('#app')