我的全局函数很少,我在 main.js 中定义如下:
Vue.prototype._isMobile = function () {
return $(window).width() < 768
}
//Few more such things
我想转移到其他文件中说 util.js ,如下所示:
return (function () {
import Vue from 'vue'
Vue.prototype._isMobile = function () {
return $(window).width() < 768
}
})();
并在 main.js
中添加了以下代码require('util.js')
我尝试了更多这方面的变种,但这不起作用,我也尝试导出,导入但这些也没有用。什么应该是做这种事情的更好方法。
我尝试使用插件的建议,我创建文件: util.js 如下:
Util.install = function (Vue, options) {
Vue.prototype._isMobile = function () {
return $(window).width() < 768
}
}
并在 main.js :
import Util from 'util'
Vue.use(Util)
但是出现此错误:
未捕获的TypeError:plugin.apply不是函数
答案 0 :(得分:2)
我可以根据您的问题使用plugins来简化和模块化。
将此添加到 utils.js
const customPlugin = {}
customPlugin.install = (Vue, options) => {
Vue.prototype._isMobile = () => {
return $(window).width() < 768
}
}
export default customPlugin
然后在您的main.js
中,您可以像使用任何其他插件一样使用它:
import customPlugin from '/path/to/customPlugin'
Vue.use(customPlugin)