1.

How to use routing in Vue.js?

Answer»

To use routing in VUE JS, we have to follow the below MENTIONED steps.

Example <UL>
  • Create three component files, as SHOWN below.
  •             // Home.vue

                <template>

                 <h1>Home</h1>

               </template>

               <script>

              export default  {

                 }

               </script>

    • Now, create About.vue file with the following syntax.

               // About.vue

                <template>

                <h1>About us</h1>

               </template>

               <script>

                   export default {

                    }

               </script>

    • Create the Contact.vue file with the below mentioned syntax.

                // Contact.vue

                 <template>

                 <h1>Contact us</h1>

                 </template>

                 <script>

                  export default {

                  }

                </script>

    • To proceed, now update the update index.html file and continue by adding app id attribute.
    • Import the Vue-router module in the main.js file from a node_modules folder and copy the below-mentioned code to the main.js file.

               // main.js

                import Vue from 'vue';

                import VueRouter from 'vue-router';

                Vue.use(VueRouter);

               import Home from './components/Home.vue';

               import About from './components/About.vue';

               import Contact from './components/Contact.vue';

                 const router = new VueRouter({

                mode: 'history',

                base: __dirname,

                routes: [

                { PATH: '/', component: Home },

                { path: '/about', component: About },

                { path: '/contact', component: Contact }

                ]

            });

         new Vue({

                router,

                template: `

                <div>

                 <nav class="navbar navbar-toggleable-md navbar-light bg-faded">

                 <div class="collapse navbar-collapse" id="navbarNav">

                 <ul class="navbar-nav">

                     <li class="nav-item"><router-link to="/" class="nav-link">Home</router-link></li>

                     <li class="nav-item"><router-link to="/about" class="nav-link">About</router-link></li>

                     <li class="nav-item"><router-link to="/contact" class="nav-link">Contact</router-link></li>

                 </ul>

             </div>

          </nav>

          <router-view class="view"></router-view>

          </div>

            }).$mount('#app');

    • Run the code and get the final output.


    Discussion

    No Comment Found