Home > Web Front-end > Vue.js > body text

How to use vue.prototype

coldplay.xixi
Release: 2020-11-30 17:03:42
Original
3666 people have browsed it

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.

How to use vue.prototype

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'
Copy after login

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)
  }
})
Copy after login

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'
Copy after login

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)
  }
})
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!