Vue router in Laravel Project
Today we are going to install a “Vue Router” in our laravel application. Using Vue routes we can change pages without refreshing page. It is so quick and these days Developers prefer Vue frontend with laravel backend.
Installation
Now I hope you guys have Laravel project ready and we are going to install Vue router straight away. Laravel has Vue pre-installed.
To install a router we use “npm” method.
open the terminal and using terminal go in the project directory. Now run below-given command to install Vue router.
npm install vue-router
it should look like this
Now in the Laravel project go into “Resources/app.js”.
And in this file add below given lines of code.
import VueRouter from 'vue-router' Vue.use(VueRouter)
Once this step is complete. Now we can add router tag in our file as shown below.
Go to about us //on click will open about us page(component)Go to Buy //on click will open buy component// will output the component output
In above code we have a div with id of “app”.Vue will display output in this div as id “add” is coming from the instance.
const app = new Vue({ el: '#app', });
Here instance of vue defining “app” element. So we have “#app” in div. If you want to change it from app to any other name you will have to edit instance code in “Resources/app.js”.
To use components we need to create them in the components folder. Here is the code for component “about”
About ComponentI'm an example component.
and include them in “resources/app.js” by importing
import about from './components/About'
Route links will work ,Once we have defined routes
We need to add routes telling what route link should do
const routes = [ { path: '/aboutus', component: about }, { path: '/buy', component: buy } ]
In above code we have routes array, And it shows what path will show what component.Here path should be equal to the “route-link’s”.
On click of
aboutus component will display content as it is defined here
{ path: '/aboutus', component: aboutus },
We also need to add router instance in “resources/app.js”. Buy adding
const router = new VueRouter({ routes // it is an array defined in above code })
At last, we need to add router instance to Vue instance
const app = new Vue({ el: '#app', router })
Make sure you run “npm run watch” to see changes
Now router is all set. Enjoy
On view file, if you find “router-link” is not clickable then add
at the bottom of the page,It will be working
You must log in to post a comment.