Home >Web Front-end >Vue.js >How to use vue.prototype
How to use vue.prototype: Define it on the prototype to make it available in each Vue instance. The code is [Vue.prototype.$appName = 'My App'], and the console will print out My App.
The operating environment of this tutorial: windows10 system, vue2.5.2, this article is applicable to all brands of computers.
[Related article recommendations: vue.js]
How to use vue.prototype:
at In the vue project main.js file:
Vue.prototype.$appName = 'My App'
This way you can make them available in every instance of Vue by defining them on the prototype.
new Vue({ beforeCreate: function () { console.log(this.$appName) } })
The console will print out My App. It's that simple!
"Why does appName start with $
? Is it important? What happens to it?"
$
is in all instances of Vue A simple convention for available properties. Doing so will avoid conflicts with defined data, methods, and computed properties.
For example, write:
Vue.prototype.appName = 'My App'
In the vue instance:
new Vue({ data: { appName: 'The name of some other app' }, beforeCreate: function () { console.log(this.appName) }, created: function () { console.log(this.appName) } })
"My App" will appear first in the log, and then "The name of some other app" will appear, because this.appName is overwritten by data after the instance is created. We prevent this from happening by $
setting scopes for instance properties. You can also use your own convention, such as $_appName
or ΩappName
, if you prefer, to avoid conflicts with plugins or future plugins.
Related free learning recommendations: JavaScript (video)
The above is the detailed content of How to use vue.prototype. For more information, please follow other related articles on the PHP Chinese website!