Vue中的 export 关键字

在 Vue.js 中,以及在现代 JavaScript 模块系统中,export 关键字用于从模块中导出功能、对象、变量或类,以便它们可以在其他模块中被导入(import)和使用。具体来说:

  1. 导出变量
    你可以导出单个变量,这样其他模块就可以使用它。

    
    

    javascript复制代码

    // 在一个文件中(例如 utils.js)
    const myVariable = 42;
    export { myVariable };
    // 或者使用简写形式
    export const myVariable = 42;
    // 在另一个文件中
    import { myVariable } from './utils.js';
    console.log(myVariable); // 输出 42
  2. 导出函数
    函数是模块中经常导出的内容之一。

    
    

    javascript复制代码

    // 在一个文件中(例如 math.js)
    function add(a, b) {
    return a + b;
    }
    export { add };
    // 或者使用简写形式
    export function add(a, b) {
    return a + b;
    }
    // 在另一个文件中
    import { add } from './math.js';
    console.log(add(2, 3)); // 输出 5
  3. 导出类
    类也可以被导出。

    
    

    javascript复制代码

    // 在一个文件中(例如 Person.js)
    export class Person {
    constructor(name) {
    this.name = name;
    }
    greet() {
    console.log(`Hello, my name is ${this.name}`);
    }
    }
    // 在另一个文件中
    import { Person } from './Person.js';
    const person = new Person('Alice');
    person.greet(); // 输出 "Hello, my name is Alice"
  4. 导出默认
    每个模块可以有一个默认导出,这通常用于导出单个函数、类或对象。

    
    

    javascript复制代码

    // 在一个文件中(例如 defaultExport.js)
    const defaultFunction = () => {
    console.log('This is the default function');
    };
    export default defaultFunction;
    // 或者导出一个类
    class DefaultClass {
    // ... 类定义
    }
    export default DefaultClass;
    // 在另一个文件中
    import defaultFunction from './defaultExport.js'; // 根据实际导出的内容选择名称
    defaultFunction(); // 输出 "This is the default function"
    // 或者
    import DefaultClass from './defaultExport.js'; // 假设这里导出了类
    const instance = new DefaultClass();
  5. 导出文件
    实际上,你不能直接“导出文件”,但你可以从文件中导出多个绑定(变量、函数、类等),然后在其他文件中导入这些绑定。这通常是通过将相关的功能组织在一个模块文件中,并从该文件导出所需的绑定来实现的。

    
    

    javascript复制代码

    // 在一个文件中(例如 module.js)
    export const foo = () => { /* ... */ };
    export const bar = () => { /* ... */ };
    // 在另一个文件中
    import { foo, bar } from './module.js';

请注意,当你使用 export 时,你实际上是在定义模块的公共接口,这决定了哪些功能对外部可见。import 语句则用于在其他模块中引入这些功能。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值