Routing in Vue
In a single-page application like this, a routing library in the UI interprets the URL path and renders an appropriate page for that path.
Vue Router
The routing library you’ll be using in the app is
Vue Router. It provides a
way to create routes and navigate between them. For example, the app’s home URL
at /
will render a list of posts, while /post/0x123
will render the Vue
component for the post with id 0x123
.
Adding the router to your project is simple. Use the below command:
vue add router
Add components
You’ll need components for the app to route to the various URLs. Create a
src/components
directory, and then components for the home page
(components/Home.vue
) and posts (components/Post.vue
), with the following
file content:
// views/Home.vue
<template>
<div>Home</div>
</template>
<script>
export default {
name: 'Home'
}
</script>
// views/Post.vue
<template>
<div>Post</div>
</template>
<script>
export default {
name: 'Home'
}
</script>
You can leave those as boilerplate for now and fill them in when you add GraphQL queries in the next step of this tutorial.
Add routing
With the boilerplate components in place, you are now ready to add the routing
logic to your app. Edit src/router/index.js
to add routes for the home
and post
views,
as shown below.
Note that the base URL points to the home
component and /post/:id
to the post
component. In the post component, id
is used to get the data for the right post:
...
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from "./components/Home.vue";
import Post from "./components/Post.vue";
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/post/:id',
name: 'Post',
component: Post
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
Let’s also edit our App.vue to display the current route.
<template>
<div>
<div class="app-banner">
...
<div class="App">
<div class="mt-4 mx-8">
<p>
Learn about building GraphQL apps with Dgraph Cloud at https://dgraph.io/learn
</p>
<router-view />
</div>
</div>
</div>
</template>
This Step in GitHub
This step is also available in the tutorial GitHub repo and is in the boilerplate commit.
You can run the app using the npm run serve
command, and then you can navigate to
http://localhost:3000
and http://localhost:3000/post/0x123
to see the
various pages rendered.