ES6 import语法

fromimport 是 ES6 模块系统的语法,用于导入和导出 JavaScript 模块。让我详细解释这些语法在 Vue 中的各种用法。

📦 基本导入语法

1. 命名导入 (Named Imports)

复制代码
// 从 Vue 中导入特定的 API
import { ref, reactive, computed } from 'vue'

// 从 Vue Router 中导入
import { useRouter, useRoute } from 'vue-router'

// 从工具库中导入
import { debounce, throttle } from 'lodash-es'

2. 默认导入 (Default Import)

复制代码
// 导入 Vue 组件(.vue 文件通常使用默认导出)
import HelloWorld from './components/HelloWorld.vue'
import App from './App.vue'

// 导入第三方库的默认导出
import axios from 'axios'
import _ from 'lodash'

3. 混合导入

复制代码
// 同时导入默认导出和命名导出
import Vue, { createApp } from 'vue'
import axios, { isCancel } from 'axios'

🎯 在 Vue 组件中的实际应用

组合式 API (Composition API)

复制代码
<template>
  <div>
    <p>{{ count }}</p>
    <p>{{ doubled }}</p>
    <button @click="increment">增加</button>
  </div>
</template>

<script setup>
// 从 Vue 导入需要的 API
import { ref, computed, onMounted } from 'vue'
// 导入其他工具
import { useRouter } from 'vue-router'
import { apiClient } from '@/utils/api'

// 使用导入的 API
const count = ref(0)
const doubled = computed(() => count.value * 2)
const router = useRouter()

const increment = () => {
  count.value++
}

onMounted(() => {
  console.log('组件挂载完成')
})
</script>

选项式 API (Options API)

复制代码
<script>
// 导入需要的功能
import { apiService } from '@/services/api'
import { validationMixin } from '@/mixins/validation'

export default {
  // 注册混入
  mixins: [validationMixin],
  
  data() {
    return {
      message: 'Hello Vue!'
    }
  },
  
  methods: {
    async fetchData() {
      // 使用导入的 API 服务
      const data = await apiService.getData()
      return data
    }
  }
}
</script>

🔧 常见的导入路径模式

1. 相对路径导入

复制代码
// 同一目录下的文件
import MyComponent from './MyComponent.vue'
// 上级目录
import Utils from '../utils/helpers.js'
// 深层嵌套
import Config from '../../../config.js'

2. 绝对路径导入(需要配置)

复制代码
// 使用 @ 别名(通常指向 src 目录)
import HelloWorld from '@/components/HelloWorld.vue'
import store from '@/store'
import router from '@/router'

// 使用 ~ 别名
import styles from '~/assets/styles/main.css'

3. 包导入

复制代码
// 从 node_modules 导入
import Vue from 'vue'
import axios from 'axios'
import { createPinia } from 'pinia'

⚙️ 路径别名配置

Vite 配置 (vite.config.js)

复制代码
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { fileURLToPath, URL } from 'node:url'

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url)),
      '~': fileURLToPath(new URL('./src', import.meta.url)),
    }
  }
})

Vue CLI 配置 (vue.config.js)

复制代码
const { defineConfig } = require('@vue/cli-service')
const path = require('path')

module.exports = defineConfig({
  configureWebpack: {
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'),
        '~': path.resolve(__dirname, 'src')
      }
    }
  }
})

🔄 动态导入

1. 懒加载组件

复制代码
<template>
  <div>
    <Suspense>
      <template #default>
        <AsyncComponent />
      </template>
      <template #fallback>
        <div>加载中...</div>
      </template>
    </Suspense>
  </div>
</template>

<script setup>
import { defineAsyncComponent } from 'vue'

// 动态导入组件(懒加载)
const AsyncComponent = defineAsyncComponent(() =>
  import('./components/AsyncComponent.vue')
)
</script>

2. 条件导入

复制代码
// 根据条件动态导入
const loadPlugin = async () => {
  if (condition) {
    const { pluginA } = await import('./plugins/pluginA.js')
    return pluginA
  } else {
    const { pluginB } = await import('./plugins/pluginB.js')
    return pluginB
  }
}

📁 索引文件导入模式

使用 index.js 统一导出

复制代码
// src/components/index.js
export { default as Button } from './Button.vue'
export { default as Input } from './Input.vue'
export { default as Modal } from './Modal.vue'

// 然后在组件中导入
import { Button, Input, Modal } from '@/components'

批量导入

复制代码
// 批量导入所有模块
const modules = import.meta.glob('./components/*.vue')

// 或者立即导入
const modules = import.meta.glob('./components/*.vue', { eager: true })

🛠️ 实际项目示例

完整的组件导入示例

复制代码
<template>
  <div class="user-dashboard">
    <Header />
    <Sidebar />
    <main>
      <UserProfile :user="user" />
      <ActivityFeed :activities="activities" />
    </main>
    <NotificationCenter />
  </div>
</template>

<script setup>
// 从 Vue 导入组合式 API
import { ref, reactive, onMounted, computed } from 'vue'

// 从路由库导入
import { useRoute, useRouter } from 'vue-router'

// 从状态管理导入
import { useUserStore } from '@/stores/user'

// 导入工具函数
import { formatDate, debounce } from '@/utils/helpers'

// 导入子组件
import Header from '@/components/layout/Header.vue'
import Sidebar from '@/components/layout/Sidebar.vue'
import UserProfile from '@/components/user/UserProfile.vue'
import ActivityFeed from '@/components/activity/ActivityFeed.vue'
import NotificationCenter from '@/components/notification/NotificationCenter.vue'

// 使用导入的功能
const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const user = ref(null)
const activities = ref([])

// 计算属性
const userName = computed(() => user.value?.name || '游客')

// 生命周期
onMounted(async () => {
  await loadUserData()
})
</script>

💡 最佳实践

  1. 按需导入:只导入需要的功能,减少打包体积

  2. 使用别名:配置路径别名,避免复杂的相对路径

  3. 合理分组:将相关的导入分组,提高代码可读性

  4. 懒加载:对不立即需要的组件使用动态导入

这些导入语法是现代 Vue 开发的基础,熟练掌握它们对于构建可维护的 Vue 应用至关重要。

相关推荐
Forever7_7 小时前
Electron 淘汰!新的桌面端框架 更强大、更轻量化
前端·vue.js
不会敲代码17 小时前
前端组件化样式隔离实战:React CSS Modules、styled-components 与 Vue scoped 对比
css·vue.js·react.js
Angelial7 小时前
Vue3 嵌套路由 KeepAlive:动态缓存与反向配置方案
前端·vue.js
SuperEugene9 小时前
Vue状态管理扫盲篇:如何设计一个合理的全局状态树 | 用户、权限、字典、布局配置
前端·vue.js·面试
阿懂在掘金9 小时前
defineModel 是进步还是边界陷阱?双数据源组件的选择逻辑
vue.js·源码阅读
李剑一10 小时前
要闹哪样?又出现了一款新的格式化插件,尤雨溪力荐,速度提升了惊人的45倍!
前端·vue.js
阿虎儿10 小时前
React Context 详解:从入门到性能优化
前端·vue.js·react.js
滕青山13 小时前
文本行过滤/筛选 在线工具核心JS实现
前端·javascript·vue.js
时光不负努力13 小时前
ts+vue3开发规范
vue.js·typescript
梦想CAD控件13 小时前
在线CAD开发包结构与功能说明
前端·javascript·vue.js