Skip to content

Instantly share code, notes, and snippets.

@meetzaveri
Created March 23, 2018 08:01
Show Gist options
  • Save meetzaveri/745c1c3bf453f64dcd9270ac7cb59358 to your computer and use it in GitHub Desktop.
Save meetzaveri/745c1c3bf453f64dcd9270ac7cb59358 to your computer and use it in GitHub Desktop.
Adding Instance Properties in Vue

Base Example

There may be data/utilities you’d like to use in many components, but you don’t want to pollute the global scope. In these cases, you can make them available to each Vue instance by defining them on the prototype:

Vue.prototype.$appName = 'My App'

Now $appName is available on all Vue instances, even before creation. If we run:

new Vue({
  beforeCreate: function() {
    console.log(this.$appName)
  }
})

Then "My App" will be logged to the console!

The Importance of Scoping Instance Properties

You may be wondering:

“Why does appName start with $? Is that important? What does it do?

No magic is happening here. $ is a convention Vue uses for properties that are available to all instances. This avoids conflicts with any defined data, computed properties, or methods.

“Conflicts? What do you mean?”

Another great question! If you set:

Vue.prototype.appName = 'My App' Then what would you expect to be logged below?

new Vue({
  data: {
    // Uh oh - appName is *also* the name of the
    // instance property we defined!
    appName: 'The name of some other app'
  },
  beforeCreate: function() {
    console.log(this.appName)
  },
  created: function() {
    console.log(this.appName)
  }
})

It would be "My App", then "The name of some other app", because this.appName is overwritten (sort of) by data when the instance is created. We scope instance properties with $ to avoid this. You can even use your own convention if you’d like, such as $_appName or ΩappName, to prevent even conflicts with plugins or future features.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment