1.使用Vue.prototype
当项目中有多个全局方法时,可以新建一个js文件global.js
function randomString(encode = 36, number = -8) {
console.log("全局方法");
return Math.random().toString(encode).slice(number);
}
// ...
export default { randomString };
在main.js中,引入注册
import global from "@/js/global.js";
Object.keys(global).forEach((key) => {
Vue.prototype["$" + key] = global[key];
});
在使用时,不需要再导入全局变量模块,而是直接用this就可以引用了如下:
console.log(this.$randomString());
2.使用全局的mixin
,mixin
里面的methods
会和每个单文件组件methods
合并
新建一个全局的mixin文件
export default {
methods: {
globalMixinFun() {
return "minix方式:》》》》》》》》》》》》globalMixinFun";
},
},
};
在main.js中引用注册
import globalMixin from "./mixin/globalMixin";
Vue.mixin(globalMixin);
在组件中使用
console.log(this.globalMixinFun());