Introduction
Routing becomes an important feature to put in place when you have many components. Thanks to the awesome Vue.js team, this is easy using vue-router.
In this tutorial, you will see how to use vue-router while building a simple Vue.js application.
Set Up the Application
You will make use of Vue-CLI to set up your application for this tutorial. If you do not have it installed already on your machine, you can do so by running:
npm install -g vue-cli
With that done, you can set up your application using the command below.
vue init webpack router-app
You are going to be asked some questions. One of these questions is: Install vue-router? For that, enter y.
Navigate to your project folder from your terminal:
cd router-app
Run the command to install all dependencies:
npm install
Start your development server by running:
npm run dev
If you want to install vue-router manually, you can use the command below.
npm install vue-router --save
Integrate Vue-Router
When using Vue-CLI, the router gets activated by default. You can see that in your src/router/index.js file.
#src/router/index.js import Vue from 'vue' // 1 import Router from 'vue-router' // 2 import HelloWorld from '@/components/HelloWorld' // 3 Vue.use(Router) // 4 export default new Router({ // 5 routes: [ { path: '/', name: 'Hello', component: HelloWorld } ] })
- Vue is imported from vue.
- Router is imported from the vue-router package.
- HelloWorld is imported from the components folder. We'll talk more about this later.
- Router is mounted as middleware to your project.
- A default route configuration is created. The route is an array of a JavaScript object. It consists of a path, name, and component. The path gets appended to the URL of your web application. The route created above is meant for the home page. You can change the path to /hello, and it will no longer work for the home page. It will only be triggered when you visit the /hello path of your application. The component tells the route the component you want to load when that path is visited. This is the reason you imported the HelloWorld component. This route is exported as Router.
The exported Router has to be imported in your src/main.js file. This is important for the routes to work. This is taken care of when working with Vue-CLI. Your src/main.js should look like this:
#src/main.js // The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' // 1 Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', router, // 2 template: '<App/>', components: { App } })
- The router is imported from your router folder.
- The imported router is used when creating a new Vue instance.
Standard Routes
The route you saw above is an example of a standard route. A standard route is one having a path, component, and name. Let's create our own route. Try this part out yourself using the flow below.
- Create a new component called Pack. You need to have some dummy text.
- Go to your src/router/index.js, import the new component you created, and add a new path.
- Open your browser and point to the new path.
I bet you were able to do that on your own. Let's try it out together.
Here is what my Pack component looks like.
#src/components/Pack.vue <template> <div class="hello"> <h1>Pack Component</h1> <p>This is a pack component. It is supposed to be a pack of wolves, but the wolves got trap in this tiny component</p> </div> </template> <script> export default { } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> </style>
Open your router file, and it should be looking like this.
#src/router/index.js import Vue from 'vue' import Router from 'vue-router' import HelloWorld from '@/components/HelloWorld' import Pack from '@/components/Pack' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'Hello', component: HelloWorld }, { path: '/pack', name: 'Pack', component: Pack } ] })
Now point your browser to http://localhost:8080/#/pack and you should see your new page.
Routes With Parameters
The routes you have made so far are static routes. Let's see how to make dynamic routes. Open your routes file and add another route like this.
#src/router/index.js { path: '/user/:id', component: User }
Here you have your path set to /user/:id; the :id defines a parameter that allows you to pass values to the routes via the URL. From the above, it is possible to have http://localhost:8080/user/23.
The value passed to the route component, in this case, is 23, and this can be accessed in the User component.
To try this out, create a new component called User. In this component, you want to be able to access the route parameter passed through the URL. This parameter will be saved in a variable called id, and the value outputted in the template. Here is what the component should look like.
#src/components/User.vue <template> <div> <h1>User Component</h1> <p>The loaded id is: </p> <router-view></router-view> </div> </template> <script> export default { name: 'user', data () { return { id: this.$route.params.id } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> </style>
Now point your browser to http://localhost:8080/#/user/123 and you will see the parameter displayed. Change from 123 to something else, and the new value will be displayed.
Child Routes
In Vue.js, it is possible to nest routes by defining children routes. This is possible using the children property provided by Vue.js. The children routes are passed as an array of objects. In your test app, you will create a child route for profiles. The child route will be given a path and a component.
First, create a new component called Profile.vue. Here is what it should look like.
#src/components/Profile.vue <template> <div> <h1>User Profile Component</h1> <p>This is a user profile</p> </div> </template> <script> export default { name: 'profile', data () { return { } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> </style>
Open your router file. The first thing you want to do will be to import the Profile component. After doing that, add the children property to the route for the User component so your route file looks like this.
#src/router/index.js import Vue from 'vue' import Router from 'vue-router' import HelloWorld from '@/components/HelloWorld' import Pack from '@/components/Pack' import User from '@/components/User' import Profile from '../components/Profile' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'Hello', component: HelloWorld }, { path: '/pack', name: 'Pack', component: Pack }, { path: '/user/13', component: User, children: [ { path: 'profile', component: Profile } ] } ] })
Now you will be able to access this new component when you point your browser to http://localhost:8080/#/user/13/profile.
Link to Routes
At this moment, the only way to navigate in your application is by entering the URL path in the browser. This is not how you will want to build a real-world application. To link to routes in Vue.js, you'll have to make use of the <router-link>
element.
Here is how it is used:
<router-link to="/route-path">Link to the route</router-link>
For children routes, here is what it should look like.
<router-link to="/parent-route/child-route">Links to the child route</router-link>
The to
attribute contains the path to the route.
To set that up in your application, open your App.vue file and make it look like this.
#src/App.vue <template> <div id="app"> <img src="./assets/logo.png"> <div> <ul> <li><router-link to="/">Home</router-link></li> <li><router-link to="/pack">Pack</router-link></li> <li><router-link to="/user/13">User</router-link></li> <li><router-link to="/user/13/profile">Profile</router-link></li> </ul> </div> <router-view/> </div> </template> <script> export default { name: 'app' } </script> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } ul { list-style-type: none; padding: 0; } li { display: inline-block; margin: 0 10px; } a { color: #42b983; } </style>
Conclusion
Navigating from one view to another is now very easy. You can go ahead and add more views. Try adding a child route to the profile route, so the path becomes http://localhost:8080/#/user/13/profile/child-path.
In this tutorial, you learned how to set up routing in Vue.js. Going forward, you should have no issues with routing in a Vue.js application. While working on this application, you also learned about the route and params object.
I hope you enjoyed yourself.
No comments:
Post a Comment