VueJS does not have a built-in router feauture. We need to follow some additional steps to install it.
Direct Download from CDN
The latest version of vue-router is available at https://unpkg.com/vue-router/dist/vue-router.js
VueJS does not have a built-in router feauture. We need to follow some additional steps to install it.
Direct Download from CDN
The latest version of vue-router is available at https://unpkg.com/vue-router/dist/vue-router.js
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script type="text/javascript" src="https://unpkg.com/vue-router/dist/vue-router.js?v=1"></script>
</head>
<body>
<div id="app">
<p>
<router-link to = "/route1">Page 1</router-link> |
<router-link to = "/route2">Page 2</router-link>
</p>
<router-view></router-view>
</div>
<script>
const route1 = {template : '<div>Page 1</div>' }
const route2 = {template : '<div>Page 2</div>' }
const routes = [
{path: '/route1', component: route1 },
{path: '/route2', component: route2 }
];
const router = new VueRouter({
routes // short for `routes: routes`
});
var vm = new Vue ({
el: '#app',
router,
data: {
}
});
</script>
</body>
</html>
The router-link is what we use to generate the links, with "to" we set the path. the router-view, as the comment in the code says is the place where the routed component is going to render.
First we set a couple of vuejs components (route1 and route2) so we have something to bind the routes to.
Then we create the routes object with three paths configurations:
The VueRouter constructor takes the routes as the param. The router object is assigned to the main vue instance using the following piece of code.
Output