首页 > 解决方案 > 如何在组件内导出和导入多个功能?Vue.js

问题描述

在我的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); }
    }
}

我真的对这个参考感到困惑,有人可以帮我怎么做吗?

标签: vue.jsvuejs2

解决方案


您可以像这样直接导出成本:

选项 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

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

import * as Datex from '../util/Date.js

选项 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
}

选项 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
}

组件中的问题是您将其视为类而不是对象。您应该直接删除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); }
    }
}

推荐阅读