【发布时间】:2019-11-05 08:05:29
【问题描述】:
很难理解我认为应该是一项简单的任务,但我准备接受也许我正在以错误的方式处理这个问题,并愿意将我的计划改为正确的方式。
简而言之,我有一个 .js 文件,其中包含数百个在我们的应用程序中使用的对象和函数。我们正在更新我们的方法并重构一些功能。
作为一个非常基本的例子,我有:
**COMMON.JS**
const dynamicYearColumn= {
resizable: false, suppressMovable: true, sortable: true, width: 100, menuTabs: [], type: 'numericColumn',
}
const defaultPercentageColumn= {
resizable: false, suppressMovable: true, sortable: true, width: 150, menuTabs: [], type: 'numericColumn',
//comparator: customPercentageCompare,
valueFormatter: formatPercent,
cellStyle: { 'text-align': 'right' },
cellClass: function (params) { var className = numberToColorClass(params.value); return className }
}
function formatPercent(number) {
if (isNaN(number.value) == true) { return '-' }
return isFinite(numberWithCommas(parseFloat(number.value, 2).toFixed(this.defaultDecimalRounding))) ? numberWithCommas(parseFloat(number.value, 2).toFixed(this.defaultDecimalRounding)) + '%' : '?';
}
function numberWithCommas(n) {
var parts = n.toString().split("."); return parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");
}
在我的 main.js 中,我现在有:
import common from './scripts/common.js'
const commonLibrary = {
install() {
Vue.common = common
Vue.prototype.$common = common
}
}
Vue.use(commonLibrary)
这就是我失败的地方。
在我的 common.js 中,如果我将代码包含在 export default 中,我必须更改代码(删除 const 以便对象是实际的对象定义,然后 formatPercent 将无法识别。
如果我 export {dynamicYearColumn,defaultPercentageColumn} 则“有点”有效,但我仍然在 formatPercent 和 numberWithCommas 上未定义。
同样,如果我尝试创建一个 Mixin,那么这也可以,但是 Mixins 方法中的任何函数都无法识别,另外有人建议我不要将这么大的库推入 Mixins,因为这不是很好的做法。
我很欣赏那里有大量优秀示例的资源,但老实说,我真的想不出正确的术语来开始寻找工作示例。
TLDR;
我只想允许从单个 JS 文件访问大量对象和函数,并在任何组件上从我的 Vue SPA 调用。
【问题讨论】:
标签: javascript vue.js es6-modules