vue.js - 如何在组件内导出和导入多个功能?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); }
}
}
我真的对这个参考感到困惑,有人可以帮我怎么做吗?
解决方案
您可以像这样直接导出成本:
选项 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); }
}
}
推荐阅读
- python - 最多有 K 个元素的最大连续子数组
- php - 在 laravel 查询中获取字段
- hadoop - 在 pyspark 中保存中间表的最佳方法
- python - 如何获取列表中的第一个最大不同元素?
- nginx - 面临 nginx proxy_pass 的问题
- mysql - 在 NodeJS 中调用 MySQL 存储过程,但在 Result number 字段值未正确舍入(Workbench 和 MySQL 控制台中的 Workig 正确)
- postgresql - 通过Postgresql查询在Object的嵌套数组中插入UUID类型的元素
- joomla - Joomla 客户端向控制器发送多个请求
- javascript - 通过比较对象值动态数组中的对象键生成新的对象数组
- powerbi - 如何在 Power Apps 中设置必填字段