Vue中导出和导入

导入方式

1. 具名导入(最常用)✅

vue

复制代码
<script setup>
// 从vue导入具体的API
import { ref, reactive, watch, computed } from 'vue'

// 从工具模块导入
import { formatDate, debounce } from '@/utils'

const count = ref(0)
</script>

2. 默认导入✅

vue

复制代码
<script setup>
// 导入有默认导出的模块
import axios from 'axios'
import ElementPlus from 'element-plus'
import MyDefaultComponent from './MyDefaultComponent.vue'
import someDefaultExport from './someModule'

// 使用
axios.get('/api/data')
</script>

3. 命名空间导入✅

vue

复制代码
<script setup>
// 导入整个模块作为对象
import * as Vue from 'vue'
import * as Lodash from 'lodash-es'
import * as Utils from '@/utils'

// 使用
const count = Vue.ref(0)
const debouncedFn = Lodash.debounce(() => {}, 300)
</script>

4. 混合导入✅

vue

复制代码
<script setup>
// 同时导入默认导出和具名导出
import VueRouter, { RouteLocationRaw } from 'vue-router'
import axios, { AxiosResponse } from 'axios'
import MyComponent, { helperFunction } from './MyComponent.vue'

// 使用
const router = VueRouter.createRouter({ /* ... */ })
</script>

5. 动态导入✅

vue

复制代码
<script setup>
// 动态导入(按需加载)
import('vue').then(module => {
  const { ref } = module
  // 使用
})

// 或者使用async/await
const loadVue = async () => {
  const { ref, computed } = await import('vue')
  // 使用
}
</script>

导出方式

1.默认导出

一个文件只能有一个 export default ✅

javascript

复制代码
// module.js
export default function main() { /* ... */ }
// 不能再有第二个 export default

2. 命名导出

可以有无限制的具名导出。

javascript

复制代码
// utils.js
export const PI = 3.1415926
export const E = 2.71828
export function add(a, b) { return a + b }
export function multiply(a, b) { return a * b }
// 可以继续导出更多...

3. 混合导出

一个文件可以同时拥有:

  • 一个默认导出(最多一个)

  • 多个具名导出

javascript

复制代码
// mathUtils.js

// 具名导出(可以有多个)
export const PI = 3.1415926
export const E = 2.71828
export function add(a, b) { return a + b }

// 默认导出(只能有一个)
const calculator = {
  add,
  subtract: (a, b) => a - b
}
export default calculator

// 还可以继续添加具名导出
export function multiply(a, b) { return a * b }
相关推荐
李小轰_Rex8 小时前
零开销 AI 数字人方案|Live2D 数字人驱动方案分享
前端·aigc
ModyQyW8 小时前
vite-plugin-uni-manifest 0.7:在 uni-app 读取之前生成
前端·uni-app
我命由我123458 小时前
Python 实用操作 - 文件操作(打开与关闭文件、读取文件、文件写入)
java·开发语言·前端·javascript·数据库·python·java-ee
修炼的dance8 小时前
批量转码前用 ffprobe 筛一遍,36 个文件能跳过 26 个
前端
费曼学习法8 小时前
从 0 到 1 上手 Super-Agent 架构:任务拆解、工具路由与失败回滚的三段实现
前端
2026小鱼AI8 小时前
当 LLM 生成的教学设计“不合格”:结构化校验、局部重生成与并发下的质量漂移
前端
疯华整猫8 小时前
借助 Trae 复刻百度网盘“无权限摇一摇”检测:Android 传感器 AI 辅助实战
前端
deli0078 小时前
流式输出为什么一段一段蹦?拆开 SSE 分块实测 20094 个乱码
前端
不一样的少年_8 小时前
为什么你写的 Agent 一报错就死循环?很多人都漏掉了这层“错误自救与熔断”机制
前端·后端·agent
857god8 小时前
做了个匿名聊天站,我把 7 个前端坑踩了一遍
前端