Detailed explanation of using Vue.prototype in Vue

Detailed explanation of using Vue.prototype in Vue

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.
If we set:

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.
For example, the following example:

// 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
If you want to implement the function of a global variable, you need to change the attribute to a reference type.

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.
Let's use this with a method called $reverseText:

 // 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 Axios

npm 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.
Reference: https://cn.vuejs.org/v2/cookbook/adding-instance-properties.html
$ indicates that this is a property available in all Vue instances and is commonly used for methods, variables, etc.

import echarts from 'echarts'
Vue.prototype.$echarts = echarts 


2. vue.component

Register components globally,
The first parameter is the component name written when calling the component. The second parameter is the name written when introducing the component. It can be used to register custom components.

import myLoading from 'base/loading'
Vue.component('myLoading',myLoading);

3. Vue.use

It 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:
  • Analysis of the reasons why const _toStr = Object.prototype.toString is required in Vue source code

<<:  Tutorial on building an FTP server in Ubuntu 16.04

>>:  What is the file mysql-bin.000001 in mysql? Can it be deleted?

Recommend

Negative margin function introduction and usage summary

As early as in the CSS2 recommendations in 1998, t...

JavaScript manual implementation of instanceof method

1. Usage of instanceof instanceof operator is use...

MySQL download and installation details graphic tutorial

1. To download the MySQL database, visit the offi...

Detailed explanation of JavaScript data types

Table of contents 1. Literals 1.1 Numeric literal...

How to use docker to deploy front-end applications

Docker is becoming more and more popular. It can ...

How to prevent event bubbling in JavaScript

What we need to pay attention to is that the char...

JavaScript Dom Object Operations

Table of contents 1. Core 1. Get the Dom node 2. ...

Detailed explanation of Vue's monitoring method case

Monitoring method in Vue watch Notice Name: You s...

Regular expression usage in CSS selectors

Yes, CSS has regular expressions too (Amen) Two p...

Detailed explanation of the loop form item example in Vue

Sometimes we may encounter such a requirement, th...

Teach you how to monitor Tomcat's JVM memory through JConsoler

Table of contents 1. How to monitor Tomcat 2. Jav...

A brief discussion on the magic of parseInt() in JavaScript

cause The reason for writing this blog is that I ...