Introducing Vue-Router and Loading URL-Based Components Chapter 8
Installing and initializing Vue-router
Similar to how we added Vue and Vuex to our applications, you can either directly include
the library from unpkg, or head to the following URL and download a local copy for
yourself: https://unpkg.com/Vue-router. Add the JavaScript to a new HTML document,
along with Vue, and your application's JavaScript. Create an application container element,
your view, as well. In the following example, I have saved the Vue-router JavaScript file as
router.js:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="app"></div>
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript" src="js/router.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>
Initialize a new Vue instance in your application JavaScript:
new Vue({
el: '#app'
});
We are now ready to add VueRouter and utilize its power. Before we do that, however, we
need to create some very simple components which we can load and display based on the
URL. As we are going to be loading the components with the router, we don't need to
register them with Vue.component, but instead create JavaScript objects with the same
properties as we would a Vue component.
For this first exercise, we are going to create two pages—Home and About pages. Found on
most websites, these should help give you context as to what is loading where and when.
Create two templates in your HTML page for us to use:
<script type="text/x-template" id="homepage">
<div>
<h1>Hello & Welcome</h1>
<p>Welcome to my website. Feel free to browse around.</p>
</div>
</script>