Syed
Syed

Reputation: 16543

How to override global variable in vue.js?

First of all, it sounds like this situation is perfect of use eventBus but I am just experimenting. What I feel this will element the process of emitting and capturing event.

Say that in my main.js I have declared:

Vue.prototype.$someHeight = 200

in some of my component I tried to change it to:

this.$someHeight = 300

But when I use it in my vue, it still says: {{ $someHeight }} // output: 200, and I was expecting 300

So, how to override it? Is this a good practice?

Upvotes: 0

Views: 4318

Answers (1)

ravish.hacker
ravish.hacker

Reputation: 1183

Every vue component is an instance of Vue. When you define a variable (such as $someHeight) on Vue's prototype, all new components created will get their own copy of such variable.

Which means every Vue component will have its own copy of $someHeight with value of 200. Now even if you set its value to 300, all other components will have the old value of 200.

It is not a good practice. You should only define functions on prototype: Vue doc

Now you can either use Vuex for this or create a global vue instance and use it to store your global variables. Vuex recommended of-course!

Upvotes: 4

Related Questions