8

I am trying to implement simple routing with official route library.

Here is my app.js

 window.Vue = require('vue');
    window.VueRouter= require('vue-router');

    Vue.use(VueRouter);

const vt=Vue.component('example', require('./components/Example.vue'));

const router = new VueRouter({
      routes:[
        {
          path:'/test',
          component:vt
        }
    ]
})

const app = new Vue({
    el: '#app',
    router:router
});

But i got an error

app.js:11256 Uncaught TypeError: VueRouter is not a constructor

1
  • Either use vue.use(window.vueRouter) or import vueRouter from 'vue-router' or let vueRouter = require('vue-router') Commented Mar 2, 2017 at 9:09

2 Answers 2

10

This answer is for any onlookers hoping for a little more insight into the problem.

There are two solutions here.

Solution 1: ES Module Import

In Laravel's default config [at least], vue-router is expected to be imported as an es module. So, it should be done at the top of the file.

import VueRouter from 'vue-router'

Solution 2: CommonJS Require

Since vue-router router is an es module, you will have to explicitly access the default property of the CommonJS version of the module.

const VueRouter = require('vue-router').default;

Either Solution

You will have to register Vue Router with Vue.

Vue.use(VueRouter)

Sign up to request clarification or add additional context in comments.

1 Comment

Even when the solution bellow is accepted, i like this one more because of the explanation. Thanks! For those who want to implement the VueRouter and are not verry familiar with Vue, this how-to is very easy to follow: laravel-news.com/using-vue-router-laravel
7

Based on the comments finally i resolved with this import

import VueRouter from 'vue-router';
Vue.use(VueRouter);

3 Comments

Just noticed we have to put this in resources/assets/js/app.js instead of resources/assets/js/bootstrap.js
You must include this code in resources/assets/js/app.js
It works like a charm. But can you please explain what this code is doing?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.