Vue自定义函数挂到全局方法

方法一:使用Vue.prototype

//在mian.js中写入函数

Vue.prototype.getToken = function (){
  ...
}

//在所有组件里可调用函数

this.getToken();

方法二:使用exports.install+Vue.prototype

// 写好自己需要的fun.js文件

exports.install = function (Vue, options) {
    Vue.prototype.getToken = function (){
       ...
    };
};

// main.js 引入并使用

import fun from './fun'
Vue.use(fun);

//在所有组件里可调用函数

this.getToken();

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

解决方法

export default {
    install(Vue)  {
        Vue.prototype.getToken = {
           ...
        }
    }
}

方法三:使用全局变量模块文件

Global.vue文件:

在需要的地方引用进全局变量模块文件,然后通过文件里面的变量名字获取全局变量参数值。

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

你可能感兴趣的:(Vue自定义函数挂到全局方法)