How to use routing in Vue.js ? (original) (raw)

Last Updated : 02 Jul, 2021

Vue router: Vue Router helps link between the browser's URL/History and Vue's components allowing for certain paths to render whatever view is associated with it. A vue router is used in building single-page applications (SPA).

The vue-router can be set up by default while creating your new project. In this article, we will install it separately. So we can see how it works.

Project Setup and Module Installation:

Project Structure: It will look like this.

Example:

main.js `

import Vue from 'vue' import App from './App.vue' import router from './router'

Vue.config.productionTip = false

new Vue({ router, render: h => h(App) }).$mount('#app')

Home.vue

Vue logo

About.vue

This is an about page

index.js

// Requiring module import Vue from 'vue' import VueRouter from 'vue-router' import Home from '../views/Home.vue' import Profile from '../views/Profile.vue'

Vue.use(VueRouter)

const routes = [ { path: '/', name: 'Home', component: Home }, // Added our new route file named profile.vue { path: '/profile', name: 'Profile', Component: Profile

},
{
    path: '/about',
    name: 'About',
    // The route level code-splitting
    // this generates a separate chunk 
    // (about.[hash].js) for this route
    // which is lazy-loaded when the
    // route is visited.
    component:()=> import(
        /* webpackChunkName: "about" */ 
        '../views/About.vue'
    )
},

]

// Create Vue Router Object const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes })

export default router

`

Now let's add our new route to that application in our App.vue and index.js file. Before we add the new route we need to create our new component named Profile.vue in our views folder.

App.vue `

Home | About | added a new route to our app.vue file// Profile

`

The can be used to display the routing components based on the routes. When applied to an element in a template, makes that element a link that initiates the navigation to a route. Navigation opens one or more routed components in one or more locations on the page. This means when we route to another view the application just hides some information and displays the requested information.

Profile.vue `

This is a profile page

`

Step to run the application: Run the server using the following command.

npm run serve

Output: Open your browser and go to http://localhost:8080/ you will see the following output.