The way routes and routers work haven’t really changed much in Composition API. The changes are subtle and we can easily adapt to the new routing system. Here’s an example to demonstrate the same. Here in this example, we’re creating three routes with three different components:
- Home (HomeView.vue)
- Article List (ArticlesView.vue)
- Article Details (ArticleDetailsView.vue)
Here’s the main.js file where we configure the router:
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import './assets/main.css'
const app = createApp(App)
app.use(router)
app.mount('#app')
Code language: JavaScript (javascript)
And here’s the router/index.js file:
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'home',
component: HomeView,
},
{
path: '/articles',
name: 'articles',
component: () => import('../views/ArticlesView.vue'),
},
{
path: '/articleDetails/:id',
name: 'articleDetails',
component: () => import('../views/ArticleDetailsView.vue'),
},
],
})
export default router
Code language: JavaScript (javascript)
Then we have the component files for each of the views as follows:
//App.vue
<template>
<div>
<nav>
<RouterLink to="/">Home</RouterLink>
<RouterLink to="/articles">Articles</RouterLink>
</nav>
<RouterView />
</div>
</template>
Code language: HTML, XML (xml)
//HomeView.vue
<template>
<div>
Home
</div>
</template>
Code language: HTML, XML (xml)
//ArticleView.vue
<template>
<div class="posts">
<h1>Articles</h1>
<ul>
<li>
<RouterLink to="/articleDetails/article1">Article 1</RouterLink>
</li>
<li>
<RouterLink to="/articleDetails/article2">Article 2</RouterLink>
</li>
<li>
<RouterLink to="/articleDetails/article3">Article 3</RouterLink>
</li>
</ul>
</div>
</template>
Code language: HTML, XML (xml)
//ArticleDetailsView.vue
<template>
<div class="post-detail">
<h1>This is {{ $route.params.id }}!</h1>
<p>You are seeing the article content of {{ $route.params.id }} here</p>
<div>
<button @click="goToFirstArticle">Go to article 1</button>
</div>
<p><RouterLink to="/articles">< Back</RouterLink></p>
</div>
</template>
<script setup>
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()
const goToFirstArticle = () => {
router.push({
name: 'articleDetails',
params: {
id: 'article1',
},
})
}
</script>
Code language: HTML, XML (xml)