从另一个文件

时间:2017-03-02 10:57:05

标签: javascript vue.js vuejs2

我的全局函数很少,我在 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不是函数

1 个答案:

答案 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)