在我的 Date.js 中,我尝试导出多个函数,但失败并返回了一堆错误。
import moment from 'moment';
let today = moment();
const age = function(date) { return today.diff(moment(date), 'years'); }
const ageGreaterThan = function(date, age) { return age(date) > age; }
//more functions here
export default age, ageGreaterThan;
在我的 Signup.vue 中,我尝试导入上面的文件,因为它预期会失败。
import Datex from './../util/Date.js';
export default{
data(){ datex: new Datex },
methods: {
sample(val){ return this.datex.age(val); }
}
}
我真的很困惑reference ,有人可以帮我怎么做吗?
最佳答案
您可以像这样直接导出成本:
export const func
import moment from 'moment';
let today = moment();
export const age = function(date) { return today.diff(moment(date), 'years'); }
export const ageGreaterThan = function(date, ageVal) { return this.age(date) > ageVal; }
//more functions here
请注意,由于您没有使用 defaults
对象,因此导入需要使用 * as
形式
import * as Datex from '../util/Date.js
import moment from 'moment';
let today = moment();
const age = function(date) { return today.diff(moment(date), 'years'); }
const ageGreaterThan = function(date, ageVal) { return this.age(date) > ageVal; }
//more functions here
export default {
age,
ageGreaterThan,
// the other functions
}
import moment from 'moment';
let today = moment();
export default {
age(date) {
return today.diff(moment(date), 'years')
},
ageGreaterThan(date, ageVal) {
return this.age(date) > ageVal;
},
// the other functions
}
组件中的问题是您将其视为类而不是对象。您应该删除 new Datex()
并直接使用 Datex.*()
(其中 * 是函数)
如果您使用上面的选项 2 或 3,则可以通过这种方式导入。 (对于选项 1,请参阅上面的 re.using * as
)
然后在你的组件中,你做...
import Datex from '../util/Date.js';
export default{
methods: {
sample(val){ return Datex.age(val); }
}
}
或者你可以直接只导入你需要的函数
import { age, ageGreaterThan } from "../util/Date.js";
export default{
methods: {
sample(val){ return age(val); }
}
}
https://stackoverflow.com/questions/60936533/