Dynamic Pages
In this example:
pages/categories/_id.vue shows data coming from the route params.
pages/categories/index.vue fetches our mountains from our API.
step 1
install axios with the the following command
yarn add axios
create a config.js file in a common folder and paste the code below
import axios from 'axios'
export const ApiService = axios.create({
baseURL: 'pasteYourApiUrl',
})
Step 2
create _id.vue in pages/categories folder and add the following code
<template>
<div>
{{ category.title }}
</div>
</template>
<script>
import { ApiService } from '../../common/config'
export default {
async asyncData({ params }) {
const response = await ApiService.get(`categories/${params.id}`)
return {
category: response.data,
}
},
}
</script>
step 3
create route.generate.js in utils folder with the code below
You can put your route.generate.js file wherever you want
import { ApiService } from '../common/config'
export const dynamicRoutes = async () => {
const CategorieRoute = await ApiService.get('categories').then((res) => {
return res.data.map((category) => {
return {
route: '/categories/' + category.slug,
payload: category,
}
})
})
const routes = CategorieRoute
return routes
}
step 4
in nuxt.config.js file add
import { dynamicRoutes } from './utils/route.generate'
export default{
generate: {
routes: dynamicRoutes,
},
}
step 5
do
yarn generate