使用vue 時,有時需要設置公共的函數,便於在所有組件中調用或者在組件的生命周期中都可調用,這便需要自定義全局函數。以下介紹一些全局函數的定義方式。
一、所有組件可調用
1、方法一:Vue.prototype
在mian.js中寫入函數
Vue.prototype.getToken = function (){
...
}
在所有組件里可調用函數
this.getToken();
2、方法二:exports.install+Vue.prototype
寫好自己需要的公共JS文件(fun.js)
exports.install = function (Vue, options) {
Vue.prototype.getToken = function (){
...
};
};
main.js 引入並使用
import fun from './fun' // 路徑示公共JS位置決定
Vue.use(fun);
所有組件里可調用函數
this.getToken();
可能遇到的問題:在用了exports.install方法時,運行報錯exports is not defined
解決方法:
export default {
install(Vue) {
Vue.prototype.getToken = {
...
}
}
}
3、方法三:在utils下創建function.js 並導出掛載到Vue原型
# function.js
class Func {
/**
* 存儲Storage
*/
setStorage(name, content, type = "local") {
if (!name) return;
let storage;
//必須判斷是否字符串
if (typeof content !== "string") {
content = JSON.stringify(content);
}
type === "local"
? (storage = window.localStorage)
: (storage = window.sessionStorage);
storage.setItem(name, content);
}
}
export default new Func();
# utils/index.js
import Vue from "vue";
import myService from "./request";
import Func from "./function";
Vue.prototype = Object.assign(Vue.prototype, {
$axios: myService,
$F: Func,
});
//使用
this.$F.setStorage()