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!
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.