如何导出和导入组件内的多个函数?vuejs

cha*_*les 2 vue.js vuejs2

在我的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;
Run Code Online (Sandbox Code Playgroud)

在我的Signup.vue中,我尝试导入上面的文件,正如预期的那样,它失败了。

import Datex from './../util/Date.js';

export default{
    data(){ datex: new Datex },

    methods: {
        sample(val){ return this.datex.age(val); }
    }
}
Run Code Online (Sandbox Code Playgroud)

我真的对此参考感到困惑,有人可以帮助我如何做到这一点?

Dan*_*iel 10

您可以像这样直接导出 cons:

选项 1 - 使用直接导出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
Run Code Online (Sandbox Code Playgroud)

请注意,由于您没有使用defaults对象,因此导入需要使用* as表单

import * as Datex from '../util/Date.js
Run Code Online (Sandbox Code Playgroud)

选项 2 - 创建函数并包装以在默认对象中导出

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
}
Run Code Online (Sandbox Code Playgroud)

选项 3 - 直接在导出对象中定义函数

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
}
Run Code Online (Sandbox Code Playgroud)

组件中的问题在于您将其视为类而不是对象。您应该直接删除new Datex()并使用Datex.*()(其中 * 是函数)

如果您使用上面的选项 2 或 3,则可以通过这种方式导入。(对于选项 1,请参阅上面的 re.using * as)在您的组件中,您然后...

import Datex from '../util/Date.js';

export default{

    methods: {
        sample(val){ return Datex.age(val); }
    }
}
Run Code Online (Sandbox Code Playgroud)

或者您可以直接只导入您需要的功能

import { age, ageGreaterThan } from "../util/Date.js";

export default{

    methods: {
        sample(val){ return age(val); }
    }
}
Run Code Online (Sandbox Code Playgroud)