11

I have a laravel project and want use Vue.js for frontend. But i have never used something more complicated than jquery. I can't run vue-router.

In my app.js

require('./bootstrap');
require('./vue-router');
require('./routes');

window.Vue = require('vue');
     const app = new Vue({
     el: '#app',
});

Then i copy code vue-router from https://router.vuejs.org/en/installation.html

In my routes.js

const router = new VueRouter();

var App = Vue.extend({});

router.start(App, '#app');

And when i try open page in console i see next : "VueRouter is not defined"

2 Answers 2

15

You have to tell Vue to use VueRouter using the method Vue.use() first. So, do:

import VueRouter from 'vue-router'

# add this code
Vue.use(VueRouter)

var router = new VueRouter({
  routes: [
    {path: 'home', component: homeComponent} 
  ]
})

UPDATED:

First install vue-router using

npm install --save vue-router

Then import and use it like

import VueRouter from 'vue-router'

Then use it in vue

Vue.use(VueRouter)

Then define your routes:

const routes = [
 {path: '/', component: SomeComponent}
]

then initialize the router and pass it the routes

var router = new VueRouter({
  routes: routes,
  mode: 'history'
})

Pass router to vuejs then profit :)

new Vue({
  el: '#root',
  router: router
})
14
  • 1
    ok, thanks. i did window.VueRouter = require('vue-router'); Vue.use(VueRouter); but now i have error Uncaught TypeError: VueRouter is not a constructor
    – Viktor
    Dec 4, 2017 at 13:48
  • Leave window.VueRouter just do VueRouter
    – samayo
    Dec 4, 2017 at 13:50
  • can you do import VueRouter from 'vue-router' instead of require ..
    – samayo
    Dec 4, 2017 at 14:18
  • import VueRouter from 'vue-router'; Vue.use(VueRouter); now "VueRouter is not defined" again
    – Viktor
    Dec 4, 2017 at 14:43
  • 2
    Now I get the problem, please first do npm install --save vue second remove require('packages') from you app.js (line 22) third: put all the code from packages.js into app.js (on line 22) fourth: remove line 5-8 in routes.js and put it in app.js (after line 23) and in route.js put export default routes after on line 4.
    – samayo
    Dec 5, 2017 at 8:51
2

You forgot to use the Vue.use method, here's how you do it:

Vue.use(VueRouter) // use the imported router as the parameter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.