导入方式
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 }