yarn add vue-router@4
## OR
npm install vue-router@4
// routes.js
import Home from './components/Home.vue'
import ItemDetails from './components/ItemDetails.vue'
export default [
{ path: '/', component: Home },
{
path: '/items',
component: ItemDetails,
},
]
// main.js
import { createRouter } from 'vue-router'
import routes from './routes'
import { createWebHashHistory } from 'vue-router/dist/vue-router.cjs'
const router = createRouter({
routes,
history: createWebHashHistory(),
})
// main.js
import { createApp } from 'vue'
import App from './App.vue'
import { createRouter } from 'vue-router'
import routes from './routes'
import { createWebHashHistory } from 'vue-router/dist/vue-router.cjs'
const router = createRouter({
routes,
history: createWebHashHistory(),
})
const app = createApp(App)
app.use(router)
app.mount('#app')
<!-- App.vue -->
<template>
<h1 class="title">Smashing Workshop: Lesson 2</h1>
<router-view />
</template>
// main.js
import { createRouter, createWebHistory } from 'vue-router'
import routes from './routes'
const router = createRouter({
routes,
history: createWebHistory(),
})
<div>
<router-link to="/">Home</router-link>
<router-link to="/items">Items</router-link>
</div>
// routes.js
export default [
{
path: '/',
name: 'home',
component: Home,
},
{
path: '/items',
name: 'item',
component: ItemDetails,
},
]
<!-- App.vue -->
<div>
<router-link :to="{ name: 'home' }">Home</router-link>
|
<router-link :to="{ name: 'item' }">Items</router-link>
</div>
// routes.js
export default [
{
path: '/',
name: 'home',
component: Home,
},
{
path: '/items/:id',
name: 'items',
component: ItemDetails,
},
]
<router-link :to="{ name: 'items', params: { id: result.name } }">
{{ result.name }}
</router-link>
// routes.js
{
path: '/items/:id',
name: 'items',
component: ItemDetails,
props: true,
},
// routes.js
export default [
{
path: '/',
name: 'home',
component: () => import('./views/Home.vue'),
},
{
path: '/items/:id',
name: 'items',
component: () => import('./views/ItemDetails.vue'),
props: true,
},
]
// main.js
const router = createRouter({
routes,
history: createWebHistory(),
})
router.beforeEach((to, from, next) => {
const cookies = document.cookie.split(';')
const isAuthenticated = cookies.some((c) => c.includes('username'))
if (to.name !== 'login' && !isAuthenticated) {
next({ name: 'login' })
} else next()
})
//routes.js
{
path: '/login',
component: () => import('./views/Login.vue'),
name: 'login',
beforeEnter: (to, from, next) => {
// ...
}
},
// ItemDetails.vue
{
// data, methods etc
beforeRouteEnter() {
console.log(`Tracking event sent for item ${this.id}`)
}
}
//routes.js
// Make sure this route is last!
{
path: '/:pathMatch(.*)',
component: () => import('./views/NotFound.vue'),
},