Updated 31 July 2023
Vue Router is the official router for Vue.js. It deeply integrates with Vue.js core to make building Single Page Applications with Vue.js a breeze. Features include:
Installation:
Installation with npm.
1 |
npm install vue-router@4 |
Installation with yarn.
Now create “index.js” file inside routes folder into root folder of application.
Example:-
Let’s open up the “routes/index.js” file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
/** * Import createRouter and createWebHistory from vue-router */ import { createRouter, createWebHistory } from 'vue-router'; /** * Views */ import Home from '../views/home.vue'; import Contact from '../views/contact.vue'; import About from '../views/about.vue'; /** * Application routes here */ const routes = [ { path: '/', name: 'Home', component: Home }, { path: '/about', name: 'About', component: About }, { path: '/contact', name: 'Contact', component: Contact } ] /** * createRouter istance */ const router = createRouter({ history: createWebHistory(), routes }) /** * Export the router instance */ export default router |
We are importing createRouter and createWebHistory from the vue-router library. Next, we import the components from “views/”. On line 17 we are declaring an array of objects named routes. This array represents our routes in the application. These array items are called route objects. The first route object has a path / which means this is going to be our base URL. The component property represents what component will be rendered when the user visits this path. We will render the Home page on this path. Finally, the name property represents the name of the route.
1 2 3 4 5 6 7 8 9 10 |
<template> <div> <router-link to="/">Home</router-link> | <router-link to="/about">About</router-link> | <router-link to="/contact">Contact</router-link> </div> <!-- All routes related views(components) will be rendered here --> <router-view /> </template> |
Let’s open up the “src/main.js” file.
1 2 3 4 5 6 7 8 9 10 |
import { createApp } from 'vue'; import router from './routes/index'; import App from './App.vue'; const app = createApp(App); app.use(router); app.mount('#app'); |
Here we are importing the router from “routes/index.js” which is export named “router” and use router as global using.
1 |
app.use(router); |
Thats all for setup vue-router in your Vue Application.
If you’re looking to build something amazing with Laravel and Vue, why not consider hire laravel developers who can bring your vision to life? You can also checkout our Bagisto Extensions.
Thanks for reading..
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.