SoFunction
Updated on 2025-04-05

How to implement global variables by defining prototype properties

Vue implements global variables by defining prototype properties

If you need to set global variables, but don't want to pollute the global scope.

In this case

Global variables can be implemented by adding prototype properties in the code instantiated in Vue, making them available in each Vue instance.

.$appName = 'My App'

This way $appName is available in all Vue instances, even before the instance is created.

If we run the following code

The console will print out the My App.

new Vue({
  beforeCreate: function () {
    (this.$appName)
  }
})
  • Asked:In the above code, why does appName start with $?
  • answer:$ is a simple convention for properties that are available in all instances of Vue. Doing so will avoid conflicts with defined data, methods, and computational properties.

If we define the prototype attributes in the following way

Run the following code and what will the console print?

 = 'My App'

new Vue({
  data: {
    appName: 'The name of some other app'
  },
  beforeCreate: function () {
    //Properties in parent class    ()
  },
  created: function () {
    //Attributes of subclass rewrite    ()
  }
})

"My App" will appear first in the console log

Then "The name of some other app" appears

Because after the instance is created, it is overwritten by data

We avoid this by setting the scope for instance properties by setting $ .

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.