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

Background gradient animation effect made by css3

Achieve results Implementation Code html <h1 c...

Detailed explanation of the Docker deployment tutorial for Jenkins beginners

This article deploys Jenkins+Maven+SVN+Tomcat thr...

Ubuntu 20.04 turns on hidden recording noise reduction function (recommended)

Recently, when using kazam in Ubuntu 20.04 for re...

Implementation steps of vue-element-admin to build a backend management system

Recently, when I was working on a conference heal...

How to view and set the mysql time zone

1. Check the database time zone show variables li...

Use of Linux read command

1. Command Introduction The read command is a bui...

JavaScript flow control (branching)

Table of contents 1. Process Control 2. Sequentia...

Teach you how to quickly install Nginx in CentOS7

Table of contents 1. Overview 2. Download the Ngi...

Detailed explanation of Vue life cycle functions

Table of contents Lifecycle Functions Common life...

A brief discussion on the binary family of JS

Table of contents Overview Blob Blob in Action Bl...

Tutorial on installing MySQL 5.7.18 using RPM package

system: CentOS 7 RPM packages: mysql-community-cl...

Detailed process of compiling and installing Storm on Kylin V10 server

1 Introduction Apache Storm is a free, open sourc...

How to deploy Tencent Cloud Server from scratch

Since this is my first post, if there are any mis...