stoneferry
stoneferry

Reputation: 177

vue-router Uncaught ReferenceError: router is not defined

I'm reviewing Vue and it's router component, although I'm having some issues getting the router component to work. Error in console below:

Uncaught ReferenceError: router is not defined

Hi all,

I'm importing the Vue and VueRouter into an index.html and trying my best to read the documentation to get the router initialized, but cannot seem to it working.

In index.html:

<script type="module" src="/assets/js/main.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

In main.js:

import VueRouter from 'vue-router'

Vue.use(VueRouter)

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

var app = new Vue({
  router,
  el: '#app',
  data: {
    ...etc

Help would be appreciated...

Many thanks.

Upvotes: 2

Views: 9522

Answers (2)

Andrew Vasylchuk
Andrew Vasylchuk

Reputation: 4769

Seems like you do not have any building process, and you load Vue and Vue Router directly in browser.

To make everything work, you should follow next steps:

  1. Change the order of scripts, so your main.js goes last. Because you need Vue and Vue Router already be loaded before you init your application.
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<script type="module" src="/assets/js/main.js"></script>
  1. Remove import from your main.js as it runs directly in browser.
Vue.use(VueRouter)

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

var app = new Vue({
  router,
  el: '#app',
  data: {
    ...etc 

Upvotes: 1

Daniel
Daniel

Reputation: 35674

You can't use import VueRouter from 'vue-router' AND <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

import means it's expecting it as an npm dependency which will be bundled in the main.js file when compiled.

you need to run npm install -save vue-router or remove the import ... statement.

Upvotes: 3

Related Questions