article

Wednesday, February 23, 2022

Vue CLI How to use Vue Router

Vue CLI How to use Vue Router

# Create a new Vue project
vue create myapp
cd myapp
# start your app by running the following command
npm run serve

vue add router

C:\vuejs\myapp>vue add router

src/router/index.js
//src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import Profile from '../views/Profile.vue'
import Product from '../views/Product.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/profile',
    name: 'profile',
    component: Profile,
  },
  { path: '/product/:id', component: Product },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export default router
src/App.vue
//src/App.vue
<template>
  <div id="nav">
    <router-link to="/">Home</router-link> |
    <router-link to="/about">About</router-link> |
    <!--<router-link to="/profile">Profile</router-link> -->
    <router-link :to="{ name: 'profile', params: { username: 'cairocoders' } }" > <!--router params -->
      Profile
    </router-link>  |
    <router-link to="/product">Product</router-link> 
  </div>
  <router-view/>
</template>
src/main.js
//src/main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

createApp(App).use(router).mount('#app')
src/views/Product.vue
//src/views/Product.vue
<template>
    <div class="product">
        Product Page
    </div>
    <span>
        Looking for Product: {{ this.$route.params.id }}
    </span>
</template>
src/views/Profile.vue
//src/views/Profile.vue
<template>
    <div class="profile">
        Profile Info
    </div>
    <span>
        {{ this.$route.params.username }}
    </span>
</template>

Related Post