Creating a detail page

In order to create a detail page, we can create UserDetail.vue and follow steps similar to the previous component:

<template>
<div class="container">
<div class="user">
<div class="user__name">
<h1>{{userInfo.name}}</h1>
<p>Person ID {{$route.params.userId}}</p>
<p>Username: {{userInfo.username}}</p>
<p>Email: {{userInfo.email}}</p>
</div>
<div class="user__address" v-if="userInfo && userInfo.address">
<h1>Address</h1>
<p>Street: {{userInfo.address.street}}</p>
<p>Suite: {{userInfo.address.suite}}</p>
<p>City: {{userInfo.address.city}}</p>
<p>Zipcode: {{userInfo.address.zipcode}}</p>
<p>Lat: {{userInfo.address.geo.lat}} Lng:
{{userInfo.address.geo.lng}} </p>
</div>

<div class="user__other" >
<h1>Other</h1>
<p>Phone: {{userInfo.phone}}</p>
<p>Website: {{userInfo.website}}</p>
<p v-if="userInfo && userInfo.company">Company:
{{userInfo.company.name}}</p>
</div>
</div>
</div>
</template>

<script>
import { API } from '../../utils/api';

export default {
data() {
return {
userInfo: {},
};
},
beforeRouteEnter(to, from, next) {
next(vm =>
API.get(`users/${to.params.userId}`)
.then(response => (vm.userInfo = response.data))
.catch(err => console.error(err))
)
},
};
</script>

<style>
.container {
line-height: 2.5em;
text-align: center;
}
</style>

As there should never be more than one user inside of our detail page, the userInfo variable has been created as a JavaScript object rather than an array.

We can then add the new component to our user.routes.js:

import UserList from './UserList';
import UserDetail from './UserDetail';

export const userRoutes = [
{ path: '/', component: UserList },
{ path: '/:userId', component: UserDetail },
];

In order to link to this component, we can add router-link within our UserList component:

<template>
<ul>
<li v-for="user in users" :key="user.id">
<router-link :to="{ path: `/${user.id}` }">
{{user.name}}
</router-link>
</li>
</ul>
</template>

If we then take a look in our browser we can see that there is only one user listed with the information underneath coming from the user detail linked to that one user: