Vue.prototype定义原型属性或方法

每一个vue组件都是Vue的实例,所以组件内this可以拿到Vue.prototype上添加的属性和方法。

Vue.prototype的官方文档介绍:https://cn.vuejs.org/v2/cookbook/adding-instance-properties.html

Vue.prototype的使用方法一:如果Vue.prototype上添加的是属性

1、注册全局变量

Vue.prototype.$appName = 'My App'

2、使用全局变量

new Vue({
  beforeCreate: function () {
    console.log(this.$appName)
  }
})

注意:要在全局变量(如AppName)前面加$,防止全局变量和组件data中定义的值产生冲突

Vue.prototype的使用方法二:如果Vue.prototype上添加的是从外部引入的js,如何调用外部js中的方法?

1、引入axios

import axios from 'axios'

2、注册全局变量

Vue.prototype.axios = axios

3、使用全局变量

this.axios.post('/qrCode/analysis', {
        v: this.uatUrl + '?v=' + this.$route.query.v,
        Openid: ''
      })

注意:如果全局变量不会与组件中的变量冲突,也可以不加$,如axios

Vue.prototype的使用方法三:如果Vue.prototype上添加的是自定义的js,如何调用js中的方法?

1、在index.js文件中定义方法

export default {
  twoDimensionArr(arr, num) {
    console.log(arr)
    var newArr = JSON.parse(JSON.stringify(arr.reverse()))
    console.log(newArr)
    var finllyArr = []
    if (newArr.length < num) {
      return arr.reverse()
    } else if (num <= 0) {
      return arr.reverse()
    } else {
      for (var a in newArr) {
        var m = []
        for (var i = 0; i < num; i++) {
          m.push(newArr.pop())
        }
        m = m.filter(res => {
          return res != undefined
        })
        finllyArr.push(m)
      }
      console.log(finllyArr)
      return finllyArr
    }
  },
}

2、在main.js中引入index.js

import union from './views/common/js/index'

3、注册全局变量

Vue.prototype.$union = union

4、使用全局变量,通过this.$union.xxx即可调用index.js中的方法了。

this.lineList = this.$union.twoDimensionArr(this.priductList, 3)

Vue.prototype的使用方法四:如果Vue.prototype上添加的是方法?

1、在main.js中注册原型方法

Vue.prototype.formatNumUnit = function (num, uom) {
  let fmt = ''
  if (!num || num == null || num === '') {
    return ''
  } else {
    fmt = num + (uom == null ? '' : uom)
    fmt = fmt.replace('-', '')
  }
  return fmt
}
Vue.prototype.formatNumUnit = function (num, uom) {   // 数字拼接单位的方法
let fmt = ''
if (!num || num == null || num === '') {
return ''
} else {
fmt = num + (uom == null ? '' : uom)
fmt = fmt.replace('-', '')
}
return fmt
}

2、在组件中使用原型方法

<el-button
        type="primary"
        icon="el-icon-download"
        @click="downloadTemplate('颗粒信息-模板.xlsx')">下载模板</el-button>
<el-table-column label="数量" align="center" width="90px">
<template slot-scope="scope">{{ formatNumUnit(scope.row.totalAmount,scope.row.uom) }}</template>
原文地址:https://www.cnblogs.com/zwh0910/p/14911900.html