Complete Vue.js 2 Web Development_ Practical guide to building end-to-end web development solutions with Vue.js 2

(singke) #1
Vue Router Patterns Chapter 20

<div>
<ul>
<li v-for="post in posts" :key="post.id">{{post.title}}</li>
</ul>
</div>
</template>

<script>
import { API } from '../../utils/api';
export default {
data() {
return {
posts: [],
};
},
beforeRouteEnter(to, from, next) {
next(vm =>
API.get(`posts?userId=${to.params.userId}`)
.then(response => (vm.posts = response.data))
.catch(err => console.error(err))
)
},
};
</script>

This allows us to get posts based on our userId route parameter. In order to display this


component as a child view, we'll need to register it as such within the user.routes.js:


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

export const userRoutes = [
{ path: '/', component: UserList },
{
path: '/:userId',
component: UserDetail,
children: [{ path: '/:userId', component: UserPosts }],
},
];
Free download pdf