从另一个文件执行部分代码

Execute some part of code from another file

我有几个全局函数,我在 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)

但是出现此错误:

Uncaught TypeError: plugin.apply is not a function

您可以使用 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)