全局配置

一 全局函数

转载于:https://www.cnblogs.com/kewenxin/p/8619240.html

转载于:https://www.cnblogs.com/conglvse/p/10062449.html

1. 在main.js里面直接写函数

Vue.prototype.changeData = function (){//changeData是函数名
  alert('执行成功');
}

组件中调用:

this.changeData();//直接通过this运行函数

2. 写一个模块文件,挂载到main.js上面。

base.js文件,文件位置可以放在跟main.js同一级,方便引用

exports.install = function (Vue, options) {
   Vue.prototype.text1 = function (){//全局函数1
    alert('执行成功1');
    };
    Vue.prototype.text2 = function (){//全局函数2
    alert('执行成功2');
    };
};

main.js入口文件:

import base from './base'//引用
Vue.use(base);//将全局函数当做插件来进行注册

组件里面调用:

this.text1();
this.text2();

注意:在用了exports.install方法时,运行报错exports is not defined

解决:

export default {
    install(Vue)  {
        Vue.prototype.getToken = {
           ...
        }
    }
}
原文地址:https://www.cnblogs.com/shichenzi/p/11753990.html