Vue实例与应用 #
一、创建应用实例 #
1.1 基本创建 #
javascript
import { createApp } from 'vue'
const app = createApp({
data() {
return {
message: 'Hello Vue!'
}
},
methods: {
greet() {
console.log(this.message)
}
}
})
app.mount('#app')
1.2 组合式API写法 #
javascript
import { createApp, ref } from 'vue'
const app = createApp({
setup() {
const message = ref('Hello Vue!')
function greet() {
console.log(message.value)
}
return {
message,
greet
}
}
})
app.mount('#app')
1.3 使用组件文件 #
javascript
// main.js
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
app.mount('#app')
vue
<!-- App.vue -->
<template>
<div id="app">
<h1>{{ message }}</h1>
</div>
</template>
<script setup>
import { ref } from 'vue'
const message = ref('Hello Vue!')
</script>
二、应用配置 #
2.1 全局属性 #
javascript
const app = createApp({})
// 添加全局属性
app.config.globalProperties.$http = {
get(url) {
return fetch(url)
},
post(url, data) {
return fetch(url, {
method: 'POST',
body: JSON.stringify(data)
})
}
}
// 在组件中使用
app.component('MyComponent', {
template: '<button @click="fetchData">获取数据</button>',
methods: {
async fetchData() {
const response = await this.$http.get('/api/data')
}
}
})
2.2 错误处理 #
javascript
// 全局错误处理器
app.config.errorHandler = (err, instance, info) => {
console.error('全局错误:', err)
console.error('组件实例:', instance)
console.error('错误信息:', info)
}
// 警告处理器
app.config.warnHandler = (msg, instance, trace) => {
console.warn('警告:', msg)
}
2.3 性能追踪 #
javascript
// 开启性能追踪
app.config.performance = true
// 自定义渲染器选项
app.config.compilerOptions = {
isCustomElement: (tag) => tag.startsWith('custom-'),
whitespace: 'condense',
delimiters: ['{{', '}}']
}
三、全局组件注册 #
3.1 注册全局组件 #
javascript
import { createApp } from 'vue'
import MyButton from './components/MyButton.vue'
import MyInput from './components/MyInput.vue'
const app = createApp({})
// 单个注册
app.component('MyButton', MyButton)
// 批量注册
app.component('MyInput', MyInput)
3.2 自动注册组件 #
javascript
// 使用require.context (Webpack)
const requireComponent = require.context('./components', false, /\.vue$/)
const app = createApp({})
requireComponent.keys().forEach(fileName => {
const componentConfig = requireComponent(fileName)
const componentName = fileName
.replace(/^\.\/(.*)\.\w+$/, '$1')
.replace(/([A-Z])/g, '-$1')
.toLowerCase()
app.component(componentName, componentConfig.default || componentConfig)
})
javascript
// 使用import.meta.glob (Vite)
const components = import.meta.glob('./components/*.vue')
const app = createApp({})
for (const path in components) {
const name = path
.replace('./components/', '')
.replace('.vue', '')
.replace(/([A-Z])/g, '-$1')
.toLowerCase()
components[path]().then((module) => {
app.component(name, module.default)
})
}
四、全局指令 #
4.1 注册全局指令 #
javascript
const app = createApp({})
// 注册全局指令
app.directive('focus', {
mounted(el) {
el.focus()
}
})
// 简写形式
app.directive('focus', (el) => {
el.focus()
})
4.2 指令钩子函数 #
javascript
app.directive('demo', {
// 绑定元素的父组件挂载前
created(el, binding, vnode, prevVnode) {},
// 绑定元素的父组件挂载时
beforeMount(el, binding, vnode, prevVnode) {},
// 绑定元素的父组件挂载后
mounted(el, binding, vnode, prevVnode) {
console.log('指令已挂载')
console.log('绑定值:', binding.value)
},
// 父组件更新前
beforeUpdate(el, binding, vnode, prevVnode) {},
// 父组件更新后
updated(el, binding, vnode, prevVnode) {},
// 父组件卸载前
beforeUnmount(el, binding, vnode, prevVnode) {},
// 父组件卸载后
unmounted(el, binding, vnode, prevVnode) {}
})
五、全局Mixin #
5.1 注册全局Mixin #
javascript
const app = createApp({})
// 全局mixin - 会应用到所有组件
app.mixin({
created() {
console.log('全局mixin - created')
},
methods: {
globalMethod() {
console.log('全局方法')
}
}
})
5.2 Mixin合并策略 #
javascript
// 自定义合并策略
const app = createApp({})
app.config.optionMergeStrategies.customOption = (toVal, fromVal) => {
return fromVal || toVal
}
六、Provide/Inject全局注入 #
6.1 应用级提供 #
javascript
const app = createApp({})
// 在应用级别提供
app.provide('message', 'Hello from app')
app.provide('config', {
theme: 'dark',
lang: 'zh-CN'
})
// 任何子组件都可以注入使用
app.component('ChildComponent', {
inject: ['message', 'config'],
template: '<div>{{ message }}</div>'
})
6.2 响应式全局状态 #
javascript
import { createApp, reactive, readonly } from 'vue'
const app = createApp({})
const state = reactive({
user: null,
theme: 'light'
})
// 提供只读状态
app.provide('state', readonly(state))
// 提供修改方法
app.provide('actions', {
setUser(user) {
state.user = user
},
setTheme(theme) {
state.theme = theme
}
})
七、插件系统 #
7.1 创建插件 #
javascript
// my-plugin.js
export default {
install(app, options) {
// 添加全局属性
app.config.globalProperties.$translate = (key) => {
return options[key] || key
}
// 注册全局组件
app.component('MyComponent', {
template: '<div>插件组件</div>'
})
// 注册全局指令
app.directive('my-directive', {
mounted(el, binding) {
el.textContent = binding.value
}
})
// 提供全局服务
app.provide('myService', {
doSomething() {
console.log('插件服务')
}
})
}
}
7.2 使用插件 #
javascript
import { createApp } from 'vue'
import MyPlugin from './my-plugin'
import Router from './router'
import Store from './store'
const app = createApp({})
// 使用插件
app.use(MyPlugin, {
hello: '你好',
world: '世界'
})
// 使用官方插件
app.use(Router)
app.use(Store)
app.mount('#app')
八、应用挂载 #
8.1 挂载方式 #
javascript
const app = createApp({})
// 挂载到DOM元素
app.mount('#app')
// 挂载到DOM元素对象
app.mount(document.getElementById('app'))
// 返回根组件实例
const rootComponent = app.mount('#app')
console.log(rootComponent.message)
8.2 多应用实例 #
html
<div id="app1"></div>
<div id="app2"></div>
<script>
// 创建多个独立的应用实例
const app1 = createApp({
data() {
return { message: 'App 1' }
}
})
const app2 = createApp({
data() {
return { message: 'App 2' }
}
})
app1.mount('#app1')
app2.mount('#app2')
</script>
8.3 卸载应用 #
javascript
const app = createApp({})
app.mount('#app')
// 卸载应用
app.unmount()
九、应用上下文 #
9.1 共享上下文 #
javascript
const app = createApp({})
// 获取应用上下文
const context = app._context
// 在上下文中共享数据
app.provide('sharedData', { value: 1 })
9.2 独立上下文 #
javascript
// 创建独立上下文的应用
const app1 = createApp({})
const app2 = createApp({})
// 它们的全局组件、指令等是独立的
app1.component('MyButton', { /* ... */ })
app2.component('MyButton', { /* ... */ }) // 不同的组件
十、生命周期图示 #
text
创建应用实例
│
▼
配置全局选项
├── app.component()
├── app.directive()
├── app.mixin()
├── app.use()
└── app.provide()
│
▼
挂载应用
app.mount('#app')
│
▼
组件生命周期
├── beforeCreate
├── created
├── beforeMount
├── mounted
├── beforeUpdate
├── updated
├── beforeUnmount
└── unmounted
│
▼
卸载应用
app.unmount()
十一、总结 #
| API | 说明 |
|---|---|
createApp() |
创建应用实例 |
app.mount() |
挂载应用 |
app.unmount() |
卸载应用 |
app.component() |
注册全局组件 |
app.directive() |
注册全局指令 |
app.mixin() |
注册全局混入 |
app.use() |
安装插件 |
app.provide() |
提供全局注入 |
app.config |
应用配置 |
应用实例要点:
- 每个应用都是独立的上下文
- 全局配置影响所有组件
- 插件是扩展功能的推荐方式
- 合理使用provide/inject共享状态
最后更新:2026-03-26