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); }
    }
}

我真的很困惑reference ,有人可以帮我怎么做吗?

最佳答案

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

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

https://stackoverflow.com/questions/60936533/

相关文章:

regex - PowerShell 从脚本中删除所有注释

jenkins - 在airflow中的特定时间运行任务

spring-boot - Spring WebFlux Reactive 和 Kotlin Cor

angular - 使用 ngrx 和选择器等待资源加载到守卫中

reactjs - 在 React 中使用另一个上下文中的上下文

firefox - 如何删除 Firefox 中的 X 按钮?

prometheus - 如何在普罗米修斯中获取速率的分位数

docker - 运行 docker-compose up 后数据库权限被拒绝

python - 使用 Gmail Python 发送电子邮件

java - 从 JSONObject 中删除除一个之外的所有键