Vue 全局挂载自定义函数(全局函数)、全局变量几种方式

  • Post author:
  • Post category:vue



目录


说明


一、全局挂载全局函数


前提


两种方式实现


二、全局挂载全局函数


原理


使用


注意


说明

1、添加实例 property

你可能会在很多组件里用到数据/实用工具,但是不想

污染全局作用域

。这种情况下,你可以通过在原型上定义它们使其在每个 Vue 的实例中可用。

Vue.prototype.$appName = 'My App'

这样

$appName

就在所有的 Vue 实例中可用了,甚至在实例被创建之前就可以。如果我们运行:

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

则控制台会打印出

My App

。就这么简单!



记得以$开头哦~否则会冲突!

一、全局挂载全局函数



前提


有很多函数在重复使用,所以,我们可以对这些函数进行全局挂载,省时又省力!



两种方式实现


1、方法一:

Vue.prototype

  • main.js加入
//Vue 全局挂载自定义函数
//folding为传进来的参数
//internalFolding 为函数名

Vue.prototype.internalFolding = function (folding){
    //函数内容
}
  • 在所有组件里可调用函数
this.internalFolding(folding)


这里的引用方式不推荐使用,因为所有的引用都放到main.js中显得很乱!

2、方法二:

exports.install+Vue.prototype

  • 写好自己需要的公共JS文件(folding.js)
  exports.install = function (Vue, options) {
    Vue.prototype.internalFolding = function (folding){
        if(folding){
            $(".abnormal-center-right").css("left","1%");
            }else{
             $(".abnormal-center-right").css("left","21%");
            }
    };
};  
  • main.js 引入并使用
import folding from '../static/js/folding'
Vue.use(folding);
  • 所有组件里可调用函数
this.internalFolding(this.folding) 


这里的引用方式推荐使用!

二、全局挂载全局函数



原理


1. 单独新建一个全局变量模块文件,模块中定义一些变量初始状态,用export default 暴露出去

2. 在main.js中引入,并通过Vue.prototype挂载到vue实例上面。供其他模块文件使用

3. 或者直接引入到需要的模块文件中使用

使用


1、新建

global_variable.js

文件,用于存放变量,示例如下:

const startDate = new Date(new Date() - 24 * 60 * 60 * 1000 * 30)
const endDate =  new Date()
const dataText = ''//表格置空
export default {
    startDate,
    endDate,
    dataText,
}


全局使用,示例如下:

import globalVariable from './assets/js/global_variable'
Vue.prototype.GLOBAL = globalVariable


在需要使用的模块文件中使用(无需引入,直接通过

this

使用),示例如下:

data() {
      return {
        startDate: this.GLOBAL.startDate, //开始时间
        endDate: this.GLOBAL.endDate, //结束时间
        dataText: this.GLOBAL.dataText, //表格开始置空
      };
    },


2、在需要使用的模块文件中使用(局部引用),示例如下:

这里写图片描述


局部引用方式不推荐使用。


注意


  1. property实例设置作用域非常重要,加$
  2. 在 JavaScript 中一个原型的方法会获得该实例的上下文。也就是说它们可以使用

    this

    访问数据、计算属性、方法或其它任何定义在实例上的东西。


    使用了 ES6/2015 的箭头函数,则其绑定的上下文不会正常工作。



版权声明:本文为Hei_lovely_cat原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。