vue 中 export 的用法

392 阅读1分钟

在创建 JavaScript 模块时,export语句用于从模块中导出实时绑定的函数、对象或原始值,以便其他程序可以通过import语句使用它们。被导出的绑定值依然可以在本地进行修改。在使用 import 进行导入时,这些绑定值只能被导入模块所读取,但在 export 导出模块中对这些绑定值进行修改,所修改的值也会实时地更新。

1,命名导出(每个模块包含任意数量)

// 导出单个特性
export let name1, name2, …, nameN; // also var, const
export let name1 = …, name2 = …, …, nameN; // also var, const
export function FunctionName(){...}
export class ClassName {...}

// 导出列表
export { name1, name2, …, nameN };

// 重命名导出
export { variable1 as name1, variable2 as name2, …, nameN };

// 解构导出并重命名
export const { name1, name2: bar } = o;

2,默认导出(每个模块包含一个)

// 默认导出
export default expression;
export default function () { … } // also class, function*
export default function name1() { … } // also class, function*
export { name1 as default, … };

3, 导出模块合集

// 导出模块合集

export * from …; // does not set the default export
export * as name1 from …; // Draft ECMAScript® 2O21
export { name1, name2, …, nameN } from …;
export { import1 as name1, import2 as name2, …, nameN } from …;
export { default } from …;

4,使用命名导出

// 导出 test.ts
export const a = 1

export const b = 2

// 导入
import { a, b } from '/@/utils/test'

console.log(a, b) // 1, 2

使用 * 接受所有的导出

import * as test from'/@/utils/test' 
 
console.log(test)

编辑切换为居中

添加图片注释,不超过 140 字(可选)

5,默认导出

// 导出 test.ts

export const a = 1

export const b = 2

export default {
 c: 3,
}

// 导入
// 只会导入 default
import test from '/@/utils/test'

console.log(test) // 输出 {c: 3}

// 默认和具名一起导出
import test, { a } from '/@/utils/test'

console.log(test, a) // 输出 {c: 3} 1

// 具名*导出,会导出 default
import test, * as t from '/@/utils/test'

console.log(test, t) // 输出 {c: 3} Module {Symbol(Symbol.toStringTag): 'Module'}

如果到处有默认,输出则含有default