Vue3入口文件main.js解析

python 复制代码
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import ElementPlus from "element-plus";
import "element-plus/dist/index.css";
import * as ElementPlusIconsVue from "@element-plus/icons-vue";
import zhCn from "element-plus/dist/locale/zh-cn.mjs";

const app = createApp(App);

// 注册所有图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component);
}

app.use(store);
app.use(router);
app.use(ElementPlus, {
  locale: zhCn,
});

app.mount("#app");

这是一个 Vue 3 应用的主入口文件,我来详细分析每个部分:

1. 导入依赖模块

javascript 复制代码
import { createApp } from "vue";
  • 从 Vue 3 导入 createApp 函数,这是 Vue 3 创建应用实例的新方式
  • 相比 Vue 2 的 new Vue(),Vue 3 使用函数式创建方式
javascript 复制代码
import App from "./App.vue";
import router from "./router";
import store from "./store";
  • App.vue:根组件,整个应用的入口组件
  • router:Vue Router 路由配置,用于单页面应用的路由管理
  • store:Vuex 或 Pinia 状态管理器,用于全局状态管理
javascript 复制代码
import ElementPlus from "element-plus";
import "element-plus/dist/index.css";
import * as ElementPlusIconsVue from "@element-plus/icons-vue";
import zhCn from "element-plus/dist/locale/zh-cn.mjs";
  • ElementPlus:饿了么团队开发的 Vue 3 UI 组件库
  • CSS 样式文件:ElementPlus 的样式表
  • 图标库:ElementPlus 配套的图标组件集合
  • 中文语言包:将 ElementPlus 界面设置为中文

2. 创建应用实例

javascript 复制代码
const app = createApp(App);
  • 使用 createApp() 创建 Vue 应用实例
  • 传入根组件 App 作为参数

3. 批量注册图标组件

javascript 复制代码
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component);
}
  • 遍历 ElementPlus 图标库中的所有图标
  • 将每个图标作为全局组件注册到应用中
  • 注册后可以在任何组件中直接使用这些图标,如 <Edit />, <Delete />

4. 注册插件和中间件

javascript 复制代码
app.use(store);
app.use(router);
app.use(ElementPlus, {
  locale: zhCn,
});
  • app.use(store):注册状态管理器
  • app.use(router):注册路由系统
  • app.use(ElementPlus, { locale: zhCn }):注册 ElementPlus UI 库并配置为中文语言

5. 挂载应用

javascript 复制代码
app.mount("#app");
  • 将 Vue 应用挂载到 HTML 中 id 为 "app" 的 DOM 元素上
  • 通常对应 index.html 中的 <div id="app"></div>
  1. 组件化开发 :使用 .vue 单文件组件
  2. 路由管理:集成 Vue Router 进行页面导航
  3. 状态管理:使用 Vuex/Pinia 管理全局状态
  4. UI 框架:采用 ElementPlus 提供丰富的 UI 组件
  5. 国际化:配置中文语言包
  6. 图标系统:全局注册图标组件库
相关推荐
万少1 小时前
HarmonyOS 开发必会 5 种 Builder 详解
前端·harmonyos
橙序员小站3 小时前
Agent Skill 是什么?一文讲透 Agent Skill 的设计与实现
前端·后端
炫饭第一名6 小时前
速通Canvas指北🦮——基础入门篇
前端·javascript·程序员
王晓枫6 小时前
flutter接入三方库运行报错:Error running pod install
前端·flutter
符方昊6 小时前
React 19 对比 React 16 新特性解析
前端·react.js
ssshooter6 小时前
又被 Safari 差异坑了:textContent 拿到的值居然没换行?
前端
曲折6 小时前
Cesium-气象要素PNG色斑图叠加
前端·cesium
Forever7_6 小时前
Electron 淘汰!新的桌面端框架 更强大、更轻量化
前端·vue.js
不会敲代码16 小时前
前端组件化样式隔离实战:React CSS Modules、styled-components 与 Vue scoped 对比
css·vue.js·react.js
Angelial7 小时前
Vue3 嵌套路由 KeepAlive:动态缓存与反向配置方案
前端·vue.js