在 Vue.js 项目中,main.js
(或 main.ts
)是应用的入口文件,负责初始化 Vue 实例、全局配置和挂载根组件。以下是核心内容和常见用法:
1. 基本结构(Vue 3 + 组合式 API)
import { createApp } from 'vue'
import App from './App.vue' // 根组件
// 创建应用实例并挂载到DOM
const app = createApp(App)
// ---------- 全局配置 ----------
app.config.globalProperties.$myGlobalVar = '全局变量' // 添加全局属性
// ---------- 注册全局组件/指令/插件 ----------
import MyComponent from '@/components/MyComponent.vue'
app.component('MyComponent', MyComponent) // 全局注册组件
import myPlugin from './plugins/myPlugin'
app.use(myPlugin) // 使用插件(如router、pinia等)
// ---------- 挂载到DOM ----------
app.mount('#app') // 对应public/index.html中的<div id="app"></div>
2. 关键配置项
2.1 全局资源注册
- 全局组件:
import Button from '@/components/Button.vue'
app.component('MyButton', Button) // <MyButton>可在任意模板使用
- 自定义指令:
app.directive('focus', {
mounted(el) { el.focus() }
}) // <input v-focus>
2.2 集成插件
- Router(路由):
import router from './router'
app.use(router)
- Pinia(状态管理):
import { createPinia } from 'pinia'
app.use(createPinia())
- UI库(如Element Plus):
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
app.use(ElementPlus)
3. Vue 2 vs Vue 3对比
特性 | Vue2 | Vue3 |
---|---|---|
创建实例 | new Vue() |
createApp() |
挂载方式 | new Vue({ render: h => h(App) }).$mount('#app') |
createApp(App).mount('#app') |
全局API | 直接修改Vue.prototype | 通过 app.config.globalProperties |
4. TypeScript支持(main.ts)
import { createApp } from 'vue'
import type { App as Application } from 'vue' //类型导入
const app: Application = createApp(App)
5. DevTools启用配置
//开发环境下启用DevTools
if (process.env.NODE_ENV === 'development') {
app.config.devtools = true;
}
常见问题
Q:如何扩展全局属性?
A:通过 app.config.globalProperties
:
//定义
app.config.globalProperties.$formatDate = (date) => { /*...*/ }
//组件内使用(this访问)
this.$formatDate(new Date())
Q:为什么推荐将插件单独封装?
A:保持 main.js
简洁,例如路由配置抽离到 /router/index.js
如果需要更具体的某部分代码示例或配置细节,可以进一步说明!
内容由零声教学AI助手提供,问题来源于学员提问