Vue.js Import/Export 教程

76 阅读4分钟

Vue.js Import/Export 教程

一、ES 模块基础语法

1. 导出(Export)方式

1.1 命名导出(Named Export)

可以导出多个变量、函数或类,每个都有自己的名称:

// 📁 utils.js
// 导出常量
export const PI = 3.14159;

// 导出函数
export function double(x) {
  return x * 2;
}

// 导出对象
export const config = {
  debug: true,
  timeout: 3000
};

// 先定义后导出
const name = 'Vue';
const version = '3.x';
export { name, version };
1.2 默认导出(Default Export)

每个模块只能有一个默认导出:

// 📁 utils.js
// 默认导出函数
export default function cube(x) {
  return x * x * x;
}

// 或默认导出对象
export default {
  name: 'Vue',
  version: '3.x'
};
1.3 混合导出

在同一模块中可以同时使用命名导出和默认导出:

// 📁 utils.js
export const PI = 3.14159;
export function double(x) { return x * 2; }
export default function cube(x) { return x * x * x; }
1.4 重命名导出

可以在导出时重命名:

// 📁 utils.js
export { 
  PI as CircleRatio, 
  double as multiplyByTwo 
};

2. 导入(Import)方式

2.1 导入命名导出
// 📁 main.js
// 导入特定的命名导出
import { PI, double } from './utils.js';

console.log(PI);      // 3.14159
console.log(double(2)); // 4
2.2 导入默认导出
// 📁 main.js
// 导入默认导出(可自定义名称)
import cube from './utils.js';

console.log(cube(3)); // 27
2.3 混合导入

同时导入默认导出和命名导出:

// 📁 main.js
import cube, { PI, double } from './utils.js';
2.4 重命名导入
// 📁 main.js
import { PI as CircleRatio, double as multiplyByTwo } from './utils.js';

console.log(CircleRatio);    // 3.14159
console.log(multiplyByTwo(2)); // 4
2.5 整体导入

导入模块的所有导出内容:

// 📁 main.js
import * as Utils from './utils.js';

console.log(Utils.PI);       // 3.14159
console.log(Utils.double(2)); // 4
console.log(Utils.default(3)); // 27 (默认导出)

二、Vue 中的导入导出应用

1. Vue 单文件组件(SFC)的导出

1.1 选项式 API 导出
<!-- 📁 MyComponent.vue -->
<template>
  <div>{{ message }}</div>
</template>

<script>
export default {
  name: 'MyComponent',
  data() {
    return {
      message: 'Hello Vue!'
    }
  },
  methods: {
    greet() {
      console.log(this.message);
    }
  }
}
</script>
1.2 组合式 API 导出(Vue 3)

Vue 3 中使用 <script setup> 语法糖时,组件会自动导出,无需显式导出:

<!-- 📁 MyComponent.vue -->
<template>
  <div>{{ message }}</div>
</template>

<script setup>
import { ref } from 'vue';

// 在 <script setup> 中声明的变量、函数会自动暴露给模板
const message = ref('Hello Vue 3!');

function greet() {
  console.log(message.value);
}
</script>

2. Vue 组件的导入

在父组件中导入子组件:

<!-- 📁 ParentComponent.vue -->
<template>
  <div>
    <h1>Parent Component</h1>
    <my-component />
  </div>
</template>

<script>
import MyComponent from './MyComponent.vue';

export default {
  name: 'ParentComponent',
  components: {
    MyComponent // 注册子组件
  }
}
</script>

<!-- 或在 Vue 3 的 <script setup> 中自动注册 -->
<script setup>
import MyComponent from './MyComponent.vue';
// 无需显式注册,可直接在模板中使用
</script>

3. 导入第三方库

// 导入 Vue 核心库
import { createApp, ref, reactive } from 'vue';

// 导入路由库
import { createRouter, createWebHistory } from 'vue-router';

// 导入状态管理库
import { createStore } from 'vuex';
// 或 Vue 3 中使用 Pinia
import { defineStore } from 'pinia';

// 导入 UI 组件库
import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css';

4. 导入 CSS 文件

// 导入全局 CSS
import './assets/main.css';

// 在 Vue 组件中导入样式
import 'element-plus/dist/index.css';

在 Vue 单文件组件中的 <style> 标签内导入样式:

<style>
@import './component-styles.css';
/* 组件样式 */
</style>

三、路径别名导入

在 Vue 项目中(通常使用 Webpack 或 Vite),可以配置路径别名以简化导入路径:

Vite 配置示例

// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': resolve(__dirname, './src')
    }
  }
})

使用别名导入

// 不使用别名
import MyComponent from '../../components/MyComponent.vue';

// 使用别名(@ 对应 src 目录)
import MyComponent from '@/components/MyComponent.vue';

四、实用技巧

1. 按需导入

为了减小打包体积,可以按需导入组件或函数:

// 整体导入 Element Plus
import ElementPlus from 'element-plus';

// 按需导入 Element Plus 组件
import { ElButton, ElInput } from 'element-plus';

2. 工具类的导出和导入

创建工具类文件:

// 📁 utils/formatters.js
export function formatDate(date) {
  return new Date(date).toLocaleDateString();
}

export function formatCurrency(value) {
  return ${value.toFixed(2)}`;
}

export default {
  formatDate,
  formatCurrency
};

导入并使用:

// 导入特定函数
import { formatDate } from '@/utils/formatters';
console.log(formatDate(new Date()));

// 导入整个模块
import * as formatters from '@/utils/formatters';
console.log(formatters.formatCurrency(100));

// 导入默认导出
import formatter from '@/utils/formatters';
console.log(formatter.formatDate(new Date()));

3. 导出常量配置

// 📁 constants/api.js
export const API_BASE_URL = 'https://api.example.com';
export const API_TIMEOUT = 10000;
export const HTTP_STATUS = {
  OK: 200,
  CREATED: 201,
  BAD_REQUEST: 400,
  UNAUTHORIZED: 401,
  NOT_FOUND: 404
};

五、CommonJS 与 ES 模块的区别

CommonJS(Node.js 传统模块系统)

// 导出
module.exports = {
  name: 'Vue',
  version: '3.x'
};

// 或
exports.name = 'Vue';
exports.version = '3.x';

// 导入
const Vue = require('vue');

ES 模块(现代 JavaScript 模块系统)

// 导出
export default {
  name: 'Vue',
  version: '3.x'
};

// 导入
import Vue from 'vue';

六、注意事项

  1. 路径问题:导入自定义文件时需要使用相对路径(如 ./utils.js 或使用别名 @/utils.js),而导入 npm 包时直接使用包名

  2. 导出限制:一个模块只能有一个默认导出,但可以有多个命名导出

  3. 动态导入:Vue 项目中还可以使用动态导入进行代码分割:

// 动态导入组件(懒加载)
const AsyncComponent = () => import('./MyComponent.vue');
  1. Vue 3 中的变化:Vue 3 推荐使用组合式 API 和 <script setup> 语法糖,组件会自动导出

通过掌握这些 import/export 语法和技巧,你可以在 Vue.js 项目中更有效地组织和管理代码,提高代码的可读性和可维护性。