Laravel Vue.js - easiest way to include vue-router?

Viewed 696

In bootstrap.js, I have this:

window.Vue = require('vue');
window.events = new Vue();

Now I would like to use vue-router as well purely to have access to this.$route. What is the easiest way to do this? I tried to follow the official documentation, but it's so much different than what comes with laravel:

const app = new Vue({
router
}).$mount('#app')

Thank you!

3 Answers

Here are steps to make laravel routes and vue routes work together:

1. define your vue layout

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Project</title>
    <link rel="stylesheet" href="/css/app.css">
</head>

<body>
    <div id="app"></div>
    <script src="/js/app.js"></script>
</body>
</html>

2. define your laravel route to make vue-router handle url

Route::any('{all}', function(){
    // welcome view should extend layout defined in step #1
    return view('welcome');
})->where('all', '.*');

3. setup vue with vue-router

routes.js

import DashboardPage from './components/dashboard/dashboard.vue'
import SignupPage from './components/auth/signup.vue'
import SigninPage from './components/auth/signin.vue'

export const routes = [
  { path: '/signup', component: SignupPage },
  { path: '/signin', component: SigninPage },
  { path: '/dashboard', component: DashboardPage },
  { path: '*', redirec: '/' }
];

router.js

import VueRouter from 'vue-router';
import { routes } from './routes';

export const router = new VueRouter({
  routes,
  mode: 'history'
});

export default router

main.js

import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'
import { router } from './router'

Vue.use(VueRouter);

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