We may use data/utilities in many components, but don't want to pollute the global scope. In this case, you can make them available in every Vue instance by defining them on the prototype. 1. Basic Example Add a variable to Vue.prototype in main.js Vue.prototype.$appName = 'My App' This way $appName is available in all Vue instances, even before the instance is created. new Vue({ beforeCreate: function () { console.log(this.$appName) } }) The console will print My App. It’s that simple! 2. Set the scope for the instance prototype Why does appName start with ? Is this important? There's no magic here. beginning? Is this important? There's no magic here. beginning? Is this important? There's no magic here. It is a simple convention for properties to be available in all Vue instances. Doing so will avoid conflicts with already defined data, methods, and calculated properties. Vue.prototype.appName = 'My App' So what does the following code output: new Vue({ data: { // Oops, `appName` is also an instance property name we defined! appName: 'The name of some other app' }, beforeCreate: function () { console.log(this.appName) }, created: function () { console.log(this.appName) } }) The log will show "My App" first, then "The name of some other app" because this.appName is overwritten by data after the instance is created. We prevent this from happening by scoping instance properties. You can also use your own conventions if you like, such as scoping instance properties to avoid this. You can also use your own conventions if you like, such as scoping instance properties to avoid this. You can also use your own conventions if you like, such as _appName or ΩappName, to avoid conflicts with plugins or future plugins. 3. Registering and using global variables Each component is a vue instance. Vue.prototype adds a variable, which just adds a property to each component. The value of this property is not global. // main.js import Vue from 'vue' import App from './App' import router from './router' import store from './store' Vue.config.productionTip = false Vue.prototype.$appName = 'main' new Vue({ el: '#app', store, router, components: { App }, template: '<App/>', }) // Register a property $appName for all components, assign an initial value of 'main', and all components can access this variable using this.$appName; // If no value is assigned in the component, the initial value is 'main' // home.vue <template> <div> <div @click="changeName">change name</div> <div @click="gotoTest2">goto test2</div> </div> </template> <script> export default { methods:{ changeName(){ this.$appName = "test1" }, gotoTest2(){ this.$router.push('/about') } } } </script> // about.vue <template> <div> <div>{{this.$appName}} in test2</div> </div> </template> Click change name in home and then jump to about. About still shows main in test2 Vue.prototype.$appName = { name: 'main' } Later, use this.$appName.name to change and reference the corresponding value. After entering about, it shows test1 in test2 4. Context of prototype methods In JavaScript, a prototype method gets the context of the instance, which means that you can use this to access: data, computed properties, methods, or anything else defined on the instance. // main.js Vue.prototype.$reverseText = function (propertyName) { this[propertyName] = this[propertyName] .split('') .reverse() .join('') } // Corresponding component <script> export default { data() { return { message: 'Hello' } }, created() { console.log(this.message) // => "Hello" this.$reverseText('message') console.log(this.message) // => "olleH" } } </script> 5. Application Examples 5.1 Introducing Axiosnpm install vue-axios --save npm install qs.js --save //Its function is to convert json format directly into the format required by data // main.js import Vue from 'vue' import axios from 'axios' import qs from 'qs' Vue.prototype.$axios = axios //Global registration, usage: this.$axios Vue.prototype.qs = qs //Global registration, usage: this.qs // Corresponding component <script> export default{ data(){ return { userId:666, token:'', } }, created(){ this.$axios({ method:'post', url:'api', data:this.qs.stringify({ //Here is the data sent to the backend userId:this.userId, token:this.token, }) }).then((response) =>{ //ES6 syntax is used here console.log(response) //Request successfully returned data}).catch((error) =>{ console.log(error) //Data returned when request failed}) } } </script> The difference between Vue.prototype, Vue.component and Vue.use 1. Vue.prototype If you need to use it in multiple places but don't want to pollute the global scope, define it like this and it will be available in every Vue instance. import echarts from 'echarts' Vue.prototype.$echarts = echarts 2. vue.component Register components globally, import myLoading from 'base/loading' Vue.component('myLoading',myLoading); 3. Vue.useIt is also a global registration. The difference from component is that the received parameters must have an install method, which is often used to register third-party plug-ins. import ElementUI from 'element-ui'; Vue.use(ElementUI); This concludes this article on the detailed use of Vue.prototype in Vue. For more relevant content on the use of Vue.prototype, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: Tutorial on building an FTP server in Ubuntu 16.04
>>: What is the file mysql-bin.000001 in mysql? Can it be deleted?
FTP is mainly used for file transfer, and is gene...
Multi-table query Use a single select statement t...
This article shares the installation and configur...
1. Window -> preferences to open the eclipse p...
Nginx uses regular expressions to automatically m...
The test is passed in the nodejs environment. The...
When installing Docker on Windows 10, after selec...
In actual use, it is often necessary to share the...
Here is a record of how to make a scroll bar appe...
The detailed installation process of mysql5.7.21 ...
This article summarizes the principles and usage ...
1. Introduction to Layer 4 Load Balancing What is...
1. Download the installation script - composer-se...
Table of contents 1. Variables Use meaningful nam...
This article shares the MySQL 5.7.18 MSI installa...