方法1:通过Vue.prototype实现
注册全局函数
import utils from './utils/Utils'
Vue.prototype.$utils = utils
// 或者直接
Vue.prototype.changeData = function (){//changeData是函数名
alert('执行成功');
}
页面使用
//直接通过this运行函数
this.$utils.xxx
// 或者
this.changeData();
缺点:
绑定的东西多了会使vue实例过大
每次使用都要加上this
优点:
定义简单
方法2:使用use,将全局函数当做插件来进行注册
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();
方法3:使用webpack.ProvidePlugin全局引入
vue.config.js配置
首先在vue.config
中引入webpack
和path
,然后在module.exports
的configureWebpack
对象中定义plugins
,引入你需要的js文件
完整的vue.config.js
配置如下:
const webpack = require('webpack')
const path = require("path")
module.exports = {
.......
configureWebpack: {
.........
plugins: [
new webpack.ProvidePlugin({
ROLE: path.resolve(__dirname, './src/utils/role.js') // 定义的全局函数类
})
]
}
}
对于 ES2015 模块的 default export,你必须指定模块的 default 属性:
new webpack.ProvidePlugin({
identifier: ['module-name', 'property'],
// ...etc.
});
示例:
new webpack.ProvidePlugin({
ROLE: [path.resolve(__dirname, './src/utils/role.js'), 'default'],
});
也就是通过标记default
,webpack
编译的时候就只识别export default
导出的函数;如果不标记,那就也识别export
导出函数
.eslintrc.js文件配置
加入一个globals
对象,把定义的全局函数类的属性名启用一下,不然会报错找不到该属性。
module.exports = {
"globals":{
"ROLE": true,
}
}
使用
重启项目,然后调用
ROLE.hasRole()
缺点:
该方法中如果导出的是一个动态值
export const userRoles = return rolesStore.get().map(item => item.roleName)
那么rolesStore
的变化,不会导致userRoles
的变化
如果想要userRoles
随时随地都能获取最新的值,那么可以将上面变量改成函数即可,因为函数在被调用的时候会重新执行,从而获取最新的值。
export const userRoles = () => {
return rolesStore.get().map(item => item.roleName)
}
如果函数内部使用的也是该页面的动态变量,比如rolesStore
,那么也需要将rolesStore
改成函数形式调用。
猜想原因:该全局函数方法使用的是静态模式,不会重复赋值一个变量,但是函数在被调用的时候会重新执行。
优点:
利于团队开发
不用到处import
或者require
来源
1.https://blog.csdn.net/pdd11997110103/article/details/120237458
2.https://www.cnblogs.com/jserhub/p/11671780.html