4
votes

I have created a new project using vue-cli 'vue init webpack-simple my-app' command. In that fresh installation copy, I'm trying to import vue-router in the App.vue component that was created by default. But it is giving me an error: 'Uncaught ReferenceError: Vue is not defined'. If I import the vue again in App.vue, then the app is working fine. But I already imported the vue in main.js, so why do I need to import it again in App.js? Is there any way I can use the imported vue from main.js? Here is my code:

main.js:

import Vue from 'vue'
import App from './App.vue'

new Vue({
  el: '#app',
  render: h => h(App)
})

App.vue:

<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

<script>
  import Vue from 'vue';   //**why I need to import it again? I already imported it in main.js
  import VueRouter from 'vue-router';
  Vue.use(VueRouter);

  import QuestionOne from './components/QuestionOneTemplate';

  const routes = [
    { path: '/', name: 'QuestionOne', component: QuestionOne },
  ];

  const router = new VueRouter({
    routes
  });

  window.router = router;

  export default {
    router,
    name: 'app',
    data () {
      return {
      }
    }
  }
</script>

<style lang="scss">
</style>
3

3 Answers

4
votes

Is there any way i can use the imported vue from main.js?

No, you need to import it in every file that uses Vue. The imports/requires are how things get hooked up. Rest assured, each import will be the same singleton instance.

You can get to the router from a Vue component's javascript using this.$router and this.$route without an import, or inside a template, using simply $router and $route

Not recommended, but you can assign Vue to a global in main.js, and use the global without importing.

main.js

import Vue from 'vue';
global.MyVue = Vue

App.vue

import VueRouter from 'vue-router';

MyVue.use(VueRouter);

Why

This is how ES6 links things up. Consider it wiring. If there were more than 1 Vue lib available, how would the linker know which to use? What if another library defined a variable or function called Vue? Perhaps a lib uses its own internal Vue for an event bus or other feature.

Other Thoughts

The explicit import also makes IDE autocompletion and syntax highlighting work better. Some IDEs can add the imports automatically, and that makes life easier.

1
votes

did you try this ?

import Vue from 'vue' import VueRouter from 'vue-router'

then use

Vue.use(VueRouter)

because the error message means you need to import vue first to use vue-router

0
votes

You did the right thing and you don't have to worry about importing Vue in multiple files. When you are shipping your application and build it for production, you will have only one "Vue import". If you take a look at dist folder and your bundled .js files you will notice that Vue is imported only once.