With Vue-cli, where do I declare my global variables?

Louis Ameline picture Louis Ameline · Jun 12, 2018 · Viewed 16k times · Source

In most Vue.js tutorials, I see stuff like

new Vue({
  store, // inject store to all children
  el: '#app',
  render: h => h(App)
})

But I'm using vue-cli (I'm actually using quasar) and it declares the Vue instance for me, so I don't know where I'm supposed to say that I want store to be a "Vue-wide" global variable. Where do I specify that? Thanks

Answer

Daksh Miglani picture Daksh Miglani · Jun 12, 2018

Yea, you can set those variables like this, in your entrypoint file (main.js):

Vue.store= Vue.prototype.store = 'THIS IS STORE VARIABLE';

and later access it in your vue instance like this:

<script>
export default {
  name: 'HelloWorld',
  methods: {
    yourMethod() {
        this.store // can be accessible here.
    }
  }
}
</script>

You can also see this in the vue-docs here.

Edit 1:

from the discussions in the comment sections about "no entrypoint file" in quasar's template.

what you can do is, to go to src/router/index.js, and there you will be able to get access to Vue, through which you can set a global variable like this:

...
import routes from './routes'

Vue.prototype.a = '123';

Vue.use(VueRouter)
...

and then if you console.log it in App.vue, something like this:

<script>
export default {
  name: 'App',
  mounted() {
        console.log(this.a);
  }
}
</script>

now, look at your console: enter image description here

You can also do the same in App.vue file in the script tag.