2

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.

1
  • If the second code sample is from main.js then I would suggest reordering your <script> tags to put main.js last. Otherwise, could you include the full stacktrace for the error? Commented Aug 9, 2019 at 17:00

2 Answers 2

3

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.

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

Comments

1

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 

Comments

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.